为什么框架的关联查询结果和数据库查询结果不一样

PHP代码:

$data = StoneType::with(['user'=>function($query){
        // 每个取 2 条
        return $query->where(\DB::raw('2'),'>',function($query){
            return $query->select(\DB::raw('count(id)'))->from('users as u')
                ->where('u.stone_id','=','users.stone_id')->where('u.id','>','users.id');
        });
}])->limit(4)->orderBy('sort', 'asc')->get();

生成的SQL(通过DB::getQueryLog获取):

select * from `users` where `users`.`stone_id` in (?, ?, ?, ?) and 2 > (select count(id) from `users` as `u` where `u`.`stone_id` = ? and `u`.`id` > ?)

clipboard.png

数据库查询结果(每个ID取2条出来,没问题):
clipboard.png

但是框架Model & with 查询结果却是每个stone_id的所有数据都查询出来了。点解?

阅读 3k
1 个回答

我也有类似的问题。打印出的sql在数据库里直接跑出来的数量是对的,但是laravel 执行后dd的看结果数量确不对。奇怪呢。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进