Php Laravel/Elount:替换为()表示leftjoin()或join()
正如我们所知,这对于mysql是一个糟糕的选择Php Laravel/Elount:替换为()表示leftjoin()或join(),php,mysql,eloquent,Php,Mysql,Eloquent,正如我们所知,这对于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::all();
foreach ($authors as $author) {
echo $author->name;
foreach ($author->posts as $post) {
echo $post->title;
}
}
如果我们有3个作者,每个作者有3篇文章,那么eloquent将进行4次SQL查询(1次用于作者,1次用于获取他们的文章)
这对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')
}
官方文件:谢谢爱德华多的回复。您的解决方案可行,但会生成大量SQL查询,如第一个示例:(可能缺少作用域选择方法?能否在帖子中显示添加新代码?如果表之间有一些共同名称,则需要选择。(si queres seguimos en castellano)
public function scopeTheNameYouChooseForTheScope($query)
{
return $query->leftJoin('posts', 'authors.id', '=', 'posts.author_id')
}