Laravel中Invoice模型hasOneThrough自定义关联条件报错求助
解决Laravel hasOneThrough关联中字段正负转换的报错问题
你遇到的问题是因为Laravel的hasOneThrough方法的本地键参数(第5个参数)只接受字段名字符串,不能直接传入DB::raw()表达式——框架内部会把这个参数当作数组键去处理,所以才会抛出array_key_exists类型错误。
要实现ABS(Invoice.order_id) = Shipment.id或者-Invoice.order_id = Shipment.id的关联条件,最简洁的方式是在关联定义后追加whereRaw条件,不用额外写其他代码:
方案1:使用ABS函数匹配
public function order() { return $this->hasOneThrough(Order::class, Shipment::class) ->whereRaw('ABS(invoices.order_id) = shipments.id'); }
方案2:使用负号转换匹配
public function order() { return $this->hasOneThrough(Order::class, Shipment::class) ->whereRaw('-invoices.order_id = shipments.id'); }
这种方式直接在关联链上追加自定义SQL条件,既满足了字段转换的需求,又符合Laravel关联的使用逻辑,不需要额外创建自定义关联类或者修改模型结构。
内容的提问来源于stack exchange,提问作者Elen
相关产品推荐
相关产品推荐

