How to list out all items in a nested table in Laravel

你。 提交于 2019-12-04 13:15:30

This is not achievable by native Eloquent methods. But you can use a bit of Fluent methods to join those tables. For instance:

Edit here: I've added the eager loading to Post query.

$user = User::find(1);
$posts = Post::with('blog') // Eager loads the blog this post belongs to
    ->join('blogs', 'blogs.id', '=', 'posts.blog_id')
    ->join('relationships', 'relationships.blog_id', '=', 'blogs.id')
    ->where('relationships.user_id', '=', $user->id)
    ->order_by('posts.id', 'desc') // Latest post first.
    ->limit(10) // Gets last 10 posts
    ->get('posts.*');

foreach ($posts as $post) {
    print($post->title);
}

If you also need a list of all blogs that such user is following to show on a sidebar, for instance. You can DYI instead of relying on Eloquent, which should be faster and more customizable. For instance:

$user = User::with('following')->find(1);

// This creates a dictionary for faster performance further ahead
$dictionary = array();
foreach ($user->following as $blog) {
    $dictionary[$blog->id] = $blog;
}

// Retrieves latest 10 posts from these blogs that he follows
// Obs: Notice the array_keys here
$posts = Post::where_in('blog_id', array_keys($blog_ids))
    ->order_by('posts.id', 'desc')
    ->limit(10)
    ->get();

// Hydrates all posts with their owning blogs.
// This avoids loading the blogs twice and has no effect
// on database records. It's just a helper for views.
foreach ($posts as $post) {
    $post->relationships['blog'] = $dictionary[$post->blog_id];
}

On view:

foreach ($user->following as $blog) {
    print($blog->title);
}

foreach ($posts as $post) {
    print($post->title . ' @'. $post->blog->title);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!