I have two models, Advisory & User with a many to many relationship and one pivot table as advisory_table.
I am trying to return latest Advisory for a User from this many to many relation.
I have defined the relationship in User model as
public function latestAdvisory()
{
return $this->belongsToMany(Advisory::class, 'advisory_users')
->latest()
->take(1);
}
It works fine with single record, but in the User collection, it loads this relation for the first record only. I tried to debug it and find the query generated by laravel. The query is
select `advisories`.*, `advisory_users`.`user_id` as `pivot_user_id`, `advisory_users`.`advisory_id` as `pivot_advisory_id` from `advisories` inner join `advisory_users` on `advisories`.`id` = `advisory_users`.`advisory_id` where `advisory_users`.`user_id` in (1, 22) order by `created_at` desc limit 1
I also tried to create an attribute and load the value in it, but it doesn't support eager loading and unnecessarily makes multiple db queries.