[英]Laravel/Eloquent: replace with() for leftjoin() or join()
As we know, this is a bad option for mysql 众所周知,这对于mysql来说是一个不好的选择
$authors = Authors::all();
foreach ($authors as $author) {
echo $author->name;
foreach ($author->posts as $post) {
echo $post->title;
}
}
If we have 3 authors with 3 posts each, eloquent make 4 SQL queries (1 for authors, and 1 more per author for get their posts) 如果我们有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;
}
}
This is better for mysql, because now we have only 2 SQL queires (1 for authors and 1 for posts). 这对于mysql更好,因为现在我们只有2个SQL查询器(1个用于作者,1个用于帖子)。
Queries are like: 查询就像:
select * from `authors` where `authors`.`deleted_at` is null
select * from `posts`
where `posts`.`deleted_at` is null and `author`.`id` in (?, ?, ?)
But, is it possible maintain the last PHP code but making a SQL query like this? 但是,是否可以维护最后的PHP代码,但进行这样的SQL查询呢?
select authors.*, posts.* from `authors`
left join posts on posts.author_id = authors.id
where `authors`.`deleted_at` is null
You can try local scopes. 您可以尝试本地范围。 The code won't get exactly like that, but may end like:
代码不会完全像那样,但是可能会像这样结束:
$authors = Authors::theNameYouChooseForTheScope()->get();
And you would define the scope like this: 您将定义如下范围:
public function scopeTheNameYouChooseForTheScope($query)
{
return $query->leftJoin('posts', 'authors.id', '=', 'posts.author_id')
}
Official documentatation: https://laravel.com/docs/5.5/eloquent#local-scopes 官方文档: https : //laravel.com/docs/5.5/eloquent#local-scopes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.