Laravel / Eloquent:替换为()为leftjoin()或join()

时间:2017-09-18 19:31:15

标签: php mysql eloquent

众所周知,这对于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 queires(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

1 个答案:

答案 0 :(得分:0)

您可以尝试本地范围。代码不会完全像这样,但可能会像:

结束
$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