user4451112
user4451112

Reputation: 41

Laravel 5 polymorphic relationship with pivot table

I have the following tables: different content types: content1, content2 pivot table: content_module different module types: module1, module2

I am trying to build relationships between content* tables and module* tables so that each content can have any module mixed in any order.

For example: content1 can have module1, module1, module2, module1, module2, module2

Can anyone recommend best approach on solving this issue. Should I use polymorphic relationship or raw query?

If I can use polymorphic relationship, is there an example I can look at?

Upvotes: 2

Views: 523

Answers (1)

user4451112
user4451112

Reputation: 41

I ended up writing my own function getModules() in the repository of the content model.

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;
}

This had to be done in one query to select records from content_modules and then for each record, a separate query to retrieve modules from their corresponding tables. This assumes that each module has its own table and each table has different columns.

Upvotes: 2

Related Questions