Reputation: 4173
I have a user, a gallery and a log. the relationships are like this:
user has many galleries galleries have many logs.
I would need to retrive the 5 most recent logs, from any gallery, that belong to this user. What confuses me is how can I put all galleries toghether and take the top 5 from all them toghether?
Upvotes: 1
Views: 285
Reputation: 2951
Assuming your relationship are as following:
users
id - integer
name - string
galleries
id - integer
user_id- integer
name - string
logs
id - integer
gallery_id - integer
title - string
You can use hasManyThrough Relationship (https://laravel.com/docs/7.x/eloquent-relationships#has-many-through)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get all of the logs for the user.
*/
public function logs()
{
return $this->hasManyThrough('App\Log', 'App\Gallery');
}
}
You can then retrieve the last logs using:
$logs = User::whereHas('logs', function($query){
$query->orderBy('created_at', 'desc');
})->get();
EDIT
You can't restrict the number of logs taken in the relationship. A workaround is to load the requested constrained relationship separately as explained here: https://github.com/laravel/framework/issues/18014
You can update your User Model:
/**
* Limit the relationship to only include 5 results
*/
public function onlyFiveLogs()
{
return $this->logs()->take(5);
}
And then for each $user, you can load the relationship manually:
$users->each(function($user) {
$user->load('onlyFiveLogs');
});
Upvotes: 2