polymorphism - Laravel 5 与数据透视表的多态关系

标签 polymorphism eloquent laravel-5

我有以下表格: 不同的内容类型:内容1、内容2 数据透视表:内容模块 不同的模块类型:模块1、模块2

我正在尝试在内容*表和模块*表之间建立关系,以便每个内容可以以任何顺序混合任何模块。

例如: content1 可以有 module1, module1, module2, module1, module2, module2

任何人都可以推荐解决此问题的最佳方法吗?我应该使用多态关系还是原始查询?

如果我可以使用多态关系,有可以看的示例吗?

最佳答案

我最终在内容模型的存储库中编写了自己的函数 getModules()。

public function getModules() {
    $contentableType = get_class($this->model); // this includes model's namespace like mynamespace\Content
    $contentModules = DB::table('content_modules')
                    ->select(['moduleable_id', 'moduleable_type'])
                    ->where('status', 1)
                    ->where('contentable_id', $this->model->id)
                    ->where('contentable_type', $contentableType)
                    ->orderBy('position', 'asc')
                    ->get();
    $modules = [];
    foreach ($contentModules as $cm) {
        $model = App::make('mynamespace\\' . $cm->moduleable_type);
        $record = $model->find($cm->moduleable_id);
        $modules[] = [
            'type' => strtolower($cm->moduleable_type),
            'data' => $record,
        ];
    }
    return $modules;
}

这必须在一个查询中完成,以从 content_modules 中选择记录,然后对于每条记录,使用一个单独的查询从相应的表中检索模块。这假设每个模块都有自己的表,并且每个表都有不同的列。

关于polymorphism - Laravel 5 与数据透视表的多态关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31386454/

相关文章:

c++ - 使用派生参数覆盖函数

Java多态性: non-final method Invocation

php - "cache" Eloquent 查询的最佳方式

php - 使用不同的 where 子句对同一关系进行多个联接/存在的查询

laravel - 如何从 PHPUnit 测试设置运行 Laravel Database Seeder?

c# - 在 C++ 中实现接口(interface)?

C++ 继承问题 : undefined reference to 'vtable'

php - 你能迭代一个 Eloquent 对象的属性吗?

php - 我们如何读取laravel中views文件夹中存储的html文件的内容?

php - 即使条件为 false,其他部分也不会执行 Laravel 5.2