【问题标题】:use laravel elequent inside loop在循环内使用 laravel eloquent
【发布时间】:2020-02-29 13:30:56
【问题描述】:

我在循环内有一个查询,如下所示:

$users = User::all();

foreach($users as $user) {
     $posts = Posts::where('status', 1)->where('user_id', $user->id)->get();
     // do some thing ..
}

我把上面的代码sn-p转换成下面的代码:

$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 ..
}

在第二种方式中,我在循环外创建模型的新对象并在循环内使用 where

这段代码 sn-p 更快吗?

性能提升了吗?

第二种方式运行一次查询?

注意:我的问题是关于这两个代码 sn-p 所以其他解决方案,如使用 relationshipswith() 函数对我不利

【问题讨论】:

    标签: php laravel performance eloquent


    【解决方案1】:

    这两个查询都是 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,...);
    

    【讨论】:

      猜你喜欢
      • 2014-11-23
      • 2019-06-28
      • 1970-01-01
      • 2017-05-20
      • 2018-03-20
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      相关资源
      最近更新 更多