2016-07-26 88 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