正如我们所知,这对 mysql 来说是一个糟糕的选择
$authors = Authors::all();
foreach ($authors as $author) {
echo $author->name;
foreach ($author->posts as $post) {
echo $post->title;
}
}
如果我们有 3 位作者,每人有 3 篇文章,Eloquent 会进行 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')
}
关于php - Laravel/ Eloquent : replace with() for leftjoin() or join(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46286842/