php n+1 problem and laravel预加载(orderBy排序)

场景

场景太多,基本上在一个表的场景中 如果需要嵌套它的关联表(relationship) 那么一般都会触发
eg:  Question Model And Answer Model 在问题的列表页面的一个区域展示相应的答案(一部分)
1.  1 Query
      select * from questions; 得到N条问题
2.  N Query 
    .  轮询获取问题下面的答案
       select * from answers where quersion_id = $question_id  

解决

. laravel框架预加载机制可以解决这个问题
. 预加载的原理是where in ($question_id_list)
  N+1次变成了2次查询
. 预加载还支持排序,方式:匿名函数传递$query查询器调用orderBy
    /**
     * 根据id获取包含topic多对多关系的信息
     * @param $id
     * @return mixed
     */
    public function byIdWithTopicsAndAnswers($id)
    {
        return Question::where(compact('id'))->with(['topic', 'answers' => function($query) {
            $query->orderBy('id', 'desc');
        }])->first();
    }

猜你喜欢

转载自blog.csdn.net/cominglately/article/details/80169999