您现在的位置是:网站首页 > 心得笔记
Laravel 中关联模型查询 +with 预加载中 select 必需字段
简介在用 laravel 开发时,要关联模型查询和 with 预加载做统计。因为是统计所以并没有全部查出所有字段的必要。故我在 with 中用闭包 $query->select (' 字段名’'); 但是在查询后结果是 null。也就是说关联不上。在这里记录下解决方法
先贴出代码:
//模型中关联关系 //订单-课程 public function course() { return $this->hasOne(Course::class, 'id', 'classId'); } //订单-活动 public function act() { return $this->hasOne(Act::class, 'id', 'classId'); } //订单-用户 public function user() { return $this->hasOne(User::class, 'id', 'bankDealId'); } //订单-礼品 public function trainInfo() { return $this->hasOne(TrainInfo::class, 'orderId', 'id'); }
//控制器 $list = $order->with(['user' => function ($query) { $query->select( 'name as hluser'); }])->with(['trainInfo' => function ($trainInfo) { $trainInfo->select('kidName', 'grade', 'giftNo'); }])->with(['act' => function ($act) { $act->select( 'gift as agift', 'coupon as actCoupon', 'shareHits as ashareHits'); }])->with(['course' => function ($course) { $course->select('gift as cgift', 'shareHits as cshareHits', 'coupon as courseCoupon'); } ])->where('status', 7)->where('actualPrice', '>', 0)->where('originalPrice', '>', 0)->where('referrerId', $id)->select('id', 'classId',ivationTime'...)->recent()->paginate(10);
这里执行结果:
由上可见:关联查询的结果都是null!!!
解决方案:
为什么呢?
因为不管一对一,一对多等关联,laravel
的关联查询的原理简单来说就是先分别查出模型自身的数据和关联模型的数据,再根据你定义的主键 id 和外键_id
进行关联起来组成查询结果。所以呢,模型自身的数据在 select 时,select字段必须要有定义关联时的主键
id(或自定义的关联字段),同样,关联模型的数据在 select 时的必需字段也要有定义关联时的外键_id (或自定义的关联字段).
在 with 中用闭包时 $query->select (' 自已想要的字段名 '. ' 定义的关联字段_id'); 模型自身在 ->select (' 至少要有关联的字段 id');
上面代码修改:
$list = $order->with(['user' => function ($query) { $query->select( 'id', 'name'); }])->with(['trainInfo' => function ($trainInfo) { $trainInfo->select('orderId', 'kidName', 'grade', 'giftNo'); }])->with(['act' => function ($act) { $act->select('id', 'gift as agift', 'coupon as actCoupon', 'shareHits as ashareHits'); }])->with(['course' => function ($course) { $course->select('id', 'gift as cgift', 'shareHits as cshareHits', 'coupon as courseCoupon'); } ])->where('status', 7)->where('actualPrice', '>', 0)->where('originalPrice', '>', 0)->where('referrerId', $id)->select('id', 'classId',ivationTime'...)->recent()->paginate(10);
执行代码:
可见,查询有效果了!!!