Laravel中OrderLine模型的hasManyThrough关联返回空数组如何解决?
问题原因及修复方案
1. hasManyThrough 关联参数顺序错误
Laravel hasManyThrough 方法的参数顺序要求为:hasManyThrough(目标模型, 中间模型, 中间表指向当前模型的外键, 目标表指向中间表的外键, 当前模型的本地关联键, 中间表指向目标表的本地键)
你当前的参数把中间表的关联外键写反了,正确的关联定义如下:
public function locations(): HasManyThrough { return $this->hasManyThrough( Location::class, LocationProduct::class, 'product_sku', // 中间表location_products关联order_lines的外键 'id', // locations表关联中间表的主键 'product_sku', // order_lines表的本地关联键 'location_id' // 中间表location_products关联locations的外键 ); }
2. 查询时未预加载locations关联
你当前的查询代码只预加载了product关联,没有加载locations,关联数据不会自动查询,修改查询代码如下:
$order_lines = OrderLine::query() ->where("order_id", "=", $order_id) ->with(["product", "locations"]) ->get(); return OrderLineResource::collection($order_lines);
3. Resource中whenLoaded用法错误
whenLoaded方法接收的参数是关联名称的字符串,不是直接调用关联属性,修改OrderLineResource中对应代码:
'locations' => LocationResource::collection($this->whenLoaded('locations'))
按照以上三点修改后即可正常获取关联的locations数据。
内容的提问来源于stack exchange,提问作者Gobbin
相关产品推荐
相关产品推荐

