Dynamic relationships in laravel using subqueries for belongstomany relationship

Viewed 736

As I have been following Eloquent Performance Patterns by Jonathan Reinink, he has explained how to add dynamic relationship using subquery for models with hasmany relationship. But as per my application I need to do the same for belongstomany relationship. Please help me achieve it.

Here is the example source code of the following, which achieves the said above dynamic relationship using subquery for models with hasmany relationship.

$query = User::query()
    ->addSelect(['role' => Role::select('name')
        ->whereColumn('user_id', 'users.id')
        ->latest()
        ->take(1)
    ]);
        
return $this->applySorting($query);
1 Answers

I believe you can introduce a join with pivot table in you sub select clause as

$query = User::query()
             ->addSelect(['role' => Role::select('name')
                ->join('pivot_table as pt', 'roles.id', '=', 'pt.role_id')
                ->whereColumn('pt.user_id', 'users.id')
                ->latest()
                ->take(1)
            ]);
Related