【问题标题】:Laravel : whereNull for pivotLaravel : whereNull 用于枢轴
【发布时间】:2016-11-04 15:02:48
【问题描述】:

我有一个通过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) 中为空的结果。 但是没有像 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 方法必须返回 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 中有错字:“presneter_id”。
  • 谢谢,已修改。当然这个问题与那个无关
  • 值得一试。 :) 希望你能找到错误。
  • 你试过没有->get()结尾还是使用wherePivot()方法?
  • Yes.wherePivot 不接受匿名函数,就像我们可以用查询生成器做的那样,它只接受 column,operator,value Triple

标签: laravel pivot-table relationship


【解决方案1】:

您只需要直接在关系上调用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()),这将返回查询构建器对象,这将引发异常。

【讨论】:

  • 这个不会影响关系模型上的 $this->pivotWheres[],而所有 wherePivot* 方法都会。
猜你喜欢
  • 2019-07-06
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
  • 1970-01-01
  • 2020-07-29
  • 2018-05-16
  • 1970-01-01
相关资源
最近更新 更多