gpt4 book ai didi

php - Laravel/ Eloquent : replace with() for leftjoin() or join()

转载 作者:行者123 更新时间:2023-11-29 03:20:22 25 4
gpt4 key购买 nike

正如我们所知,这对 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')
}

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

关于php - Laravel/ Eloquent : replace with() for leftjoin() or join(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46286842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com