php - 在循环内使用 laravel elequent
问题描述
我在循环内有一个查询,如下所示:
$users = User::all();
foreach($users as $user) {
$posts = Posts::where('status', 1)->where('user_id', $user->id)->get();
// do some thing ..
}
我将上面的代码片段转换为以下代码:
$users = User::all();
$posts_tmp = Posts::where('status', 1);
foreach($users as $user) {
$posts = $posts_tmp->where('user_id', $user->id)->get();
// do some thing ..
}
在第二种方式中,我在循环外创建模型的新对象并在循环内使用
这个代码片段更快吗?
性能提高了吗?
在第二种方式中运行一次查询?
注意:我的问题是关于这两个代码片段所以其他解决方案,如 use
relationships
或with()
function 对我不利
解决方案
这两个查询都是n+1 个查询。
您的查询将全部转换为:
select * from users;
select * from posts where status = 1 and user_id = 1;
select * from posts where status = 1 and user_id = 2;
select * from posts where status = 1 and user_id = 3;
...
像急切加载一样,您可以使用whereIn
而不是循环:
$users = User::all();
$posts = Posts::where('status', 1)->whereIn('user_id', $users->pluck('id')->toArray());
因此查询将转换为两个这样的 sql 查询:
select * from users;
select * from posts where status = 1 and user_id in (1,2,3,...);