2016-07-26 96 views
2

我試圖返回PostsHistory模型中沒有行的所有帖子(型號:Post)。Laravel relationship`whereNotIn`其他表

我的代碼是:

public function posts(){ 
    return $this->hasMany('App\Post'); 
} 

public function remaining_posts(){ 
    $history = PostHistory::all()->pluck('id'); 
    return $this->posts->whereNotIn('post_id', $history); 
} 

但我得到一個錯誤

[BadMethodCallException]  
    Method whereNotIn does not exist. 

有什麼辦法,我可以通過關係拿到remaining_posts或只能在控制器內完成?

回答

1

編輯您的最後一行:

return $this->posts()->whereNotIn('post_id', $history)->get(); 

  1. 您需要更改postsposts()posts是一個Illuminate\Database\Eloquent\Collection對象,它不具有whereNotIn()方法,其中posts()將返回Illuminate\Database\Eloquent\Relations\HasMany對象,該對象已定義whereNotIn()方法。

  2. whereNotIn()返回一個Illuminate\Database\Query\Builder對象。所以你需要撥打get()來獲得收藏。但是,如果您希望靈活性將其他Builder方法鏈接到您的remaining_posts()方法,請不要使用get()

+0

感謝您的解釋:) – George