2016-07-02 22 views
1

我有一個訂單(訂單型號)表通過order_items透視表相關書籍(Book模型):Laravel:whereNull爲支點

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(); 
} 

它拋出此異常:

關係方法必須返回類型照亮\數據庫\雄辯\關係\關係(查看的對象: E:\ xampp \ htdocs \ pnu \ resources \ views \ orders \ table.blade.php)(查看:E:\ xampp \ htdocs \ pnu \ resources \ views \ orders \ table.blade.php)

+0

您在whereNull中有一個錯字:「presneter_id」。 –

+0

謝謝,修改。當然這個問題是不相關的 – alex

+0

值得一試。 :)希望你找到錯誤。 –

回答

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()),這將返回查詢構建器對象,該對象將引發異常。