reinink/advanced-eloquent

[Question] Possible to apply the same technique to belongsToMany() relationship with pivot?

Opened this issue · 0 comments

There are situations where we want to retrieve a single record from belongsToMany relationship.

I was able to retrieve the related record using join through pivot table, but not able to get the pivot data because subquery select only works for single column.

// Room.php
public function lastUser()
{
    return $this->belongsTo(User::class);
}
public function scopeWithLastUser($query)
{
    $query->addSubSelect('last_user_id', User::select('user_id')
        ->join('room_user', 'room_user.user_id', '=', 'users.id')
        ->whereColumn('room_id', 'rooms.id')
        ->orderBy('room_user.created_at', 'desc')
        ->take(1)
    )->with('lastUser);
}

Do you have any idea how to achieve this?
Thanks in advance