我们知道,这对mysql来说是一个糟糕的选择

$authors = Authors::all();
foreach ($authors as $author) {
    echo $author->name;
    foreach ($author->posts as $post) {
        echo $post->title;
    }
}

如果我们有3个作者,每个作者有3篇文章,那么雄辩地进行4个SQL查询(1个用于作者,1个用于每个作者获取他们的文章)
$authors = Authors::with('posts')
        ->all();
foreach ($authors as $author) {
    echo $author->name;
    foreach ($author->posts as $post) {
        echo $post->title;
    }
}

这对于mysql更好,因为现在我们只有2个SQL查询(1个用于作者,1个用于帖子)。
查询如下:
select * from `authors` where `authors`.`deleted_at` is null

select * from `posts`
    where `posts`.`deleted_at` is null and `author`.`id` in (?, ?, ?)

但是,是否有可能维护最后一个PHP代码,但进行这样的SQL查询?
select authors.*, posts.* from `authors`
    left join posts on posts.author_id = authors.id
    where `authors`.`deleted_at` is null

最佳答案

您可以尝试本地作用域。代码不会完全这样,但可能会结束如下:

$authors = Authors::theNameYouChooseForTheScope()->get();

您可以这样定义范围:
public function scopeTheNameYouChooseForTheScope($query)
{
    return $query->leftJoin('posts', 'authors.id', '=', 'posts.author_id')
}

官方文件:https://laravel.com/docs/5.5/eloquent#local-scopes

10-04 15:01
查看更多