我有一个通过order_items
数据透视表与图书(图书模型)相关的订单(订单模型)表:
public function books()
{
return $this->morphedByMany('App\Models\Book', 'order_item')
->withPivot(['quantity', 'presenter_id', 'price', 'portion', 'settlement_id']);
}
我需要过滤数据presenter_id
透视表(order_items)中为null的结果。但是没有像这样的方法wherePivotNull
。我也尝试了以下solution(reference)但没有机会:
public function books()
{
return $this->morphedByMany('App\Models\Book', 'order_item')
->withPivot(['quantity', 'presenter_id', 'price', 'portion', 'settlement_id'])
->getQuery()->whereNull('order_items.presenter_id')->get();
}
它抛出此异常:
关系方法必须返回类型为Illuminate \ Database \ Eloquent \ Relations \ Relation的对象(视图:E:\ xampp \ htdocs \ pnu \ resources \ views \ orders \ table.blade.php)(视图:E:\ xampp \ htdocs \ pnu \ resources \ views \ orders \ table.blade.php)
您只需要whereNull()
直接调用关系即可,但是您需要确保使用透视表的名称来限定字段名称。
public function books()
{
return $this->morphedByMany('App\Models\Book', 'order_item')
->whereNull('order_items.presenter_id')
->withPivot(['quantity', 'presenter_id', 'price', 'portion', 'settlement_id']);
}
调用whereNull()
关系时,它将whereNull()
在内部调用基础查询构建器,然后返回关系对象。在您提供的示例中,您whereNull()
直接调用了查询构建器(getQuery()
首先调用),这将返回查询构建器对象,该对象将引发异常。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句