Laravel关联查询:如何在Customer结果中包含City关联数据
解决方法
要在获取Customer数据时,让关联的address字段包含完整的city数据,你可以通过嵌套预加载来实现,有几种实用方式:
1. 点语法直接嵌套加载
这是最简洁的写法,直接在with方法里用.指定多层关联关系:
Customer::with(['address.city'])->get();
执行这个查询时,会同时预加载Customer的address关联,以及address对应的city关联,返回结果里的address字段就会包含完整的city数据,而非仅city_id。
2. 闭包方式嵌套加载
如果需要给address或city的查询添加额外条件(比如筛选特定城市、只返回city的部分字段),可以用闭包实现:
Customer::with(['address' => function ($query) { // 可选:给address加额外查询条件,比如$query->where('is_default', 1); $query->with('city'); // 加载address对应的city关联 }])->get();
3. 全局自动加载关联(可选)
如果希望每次获取Address模型时都自动带上对应的City数据,可以在Address模型中设置$with属性:
class Address extends Model { protected $with = ['city']; // 自动加载city关联 // 其他模型代码... public function city() { return $this->hasOne(City::class); } }
设置后,后续调用Customer::with(['address'])->get()时,address里会自动包含完整的city数据,无需每次手动指定嵌套加载。
内容的提问来源于stack exchange,提问作者nick coder
相关产品推荐
相关产品推荐

