我正在尝试返回PostsHistory模型中没有行的所有帖子(模型:帖子)。
我的代码是:
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,或者只能在控制器中完成?
答案 0 :(得分:0)
将您的最后一行编辑为:
return $this->posts()->whereNotIn('post_id', $history)->get();
即
您需要将posts
更改为posts()
。 posts
是一个Illuminate\Database\Eloquent\Collection
对象,没有whereNotIn()
方法,posts()
将返回Illuminate\Database\Eloquent\Relations\HasMany
对象,其中定义了whereNotIn()
方法。< / p>
whereNotIn()
返回Illuminate\Database\Query\Builder
个对象。所以你需要调用get()
来获取一个集合。但是,如果您希望flexibilty将其他Builder
方法链接到您的remaining_posts()
方法,请不要使用get()
。