Laravel : whereNull for pivot
Laravel : whereNull for pivot
我有一个订单(订单模型)table 通过 order_items
枢轴 table 与图书(图书模型)相关:
public function books()
{
return $this->morphedByMany('App\Models\Book', 'order_item')
->withPivot(['quantity', 'presenter_id', 'price', 'portion', 'settlement_id']);
}
我需要过滤 presenter_id
在主元 table(order_items) 中为空的结果。
但是没有像 wherePivotNull
这样的方法。我也尝试了以下解决方案(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();
}
它抛出这个异常:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation (View: E:\xampp\htdocs\pnu\resources\views\orders\table.blade.php) (View: E:\xampp\htdocs\pnu\resources\views\orders\table.blade.php)
您只需直接在关系上调用 whereNull()
,但您需要确保使用数据透视表的名称限定字段名称 table。
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()
,然后是关系对象 return。在您提供的示例中,您直接在查询构建器上调用了 whereNull()
(首先调用 getQuery()
),这将 return 查询构建器对象,这将引发异常。
我有一个订单(订单模型)table 通过 order_items
枢轴 table 与图书(图书模型)相关:
public function books()
{
return $this->morphedByMany('App\Models\Book', 'order_item')
->withPivot(['quantity', 'presenter_id', 'price', 'portion', 'settlement_id']);
}
我需要过滤 presenter_id
在主元 table(order_items) 中为空的结果。
但是没有像 wherePivotNull
这样的方法。我也尝试了以下解决方案(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();
}
它抛出这个异常:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation (View: E:\xampp\htdocs\pnu\resources\views\orders\table.blade.php) (View: E:\xampp\htdocs\pnu\resources\views\orders\table.blade.php)
您只需直接在关系上调用 whereNull()
,但您需要确保使用数据透视表的名称限定字段名称 table。
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()
,然后是关系对象 return。在您提供的示例中,您直接在查询构建器上调用了 whereNull()
(首先调用 getQuery()
),这将 return 查询构建器对象,这将引发异常。