Laravel关系`whereNotIn`其他表

时间:2016-07-26 10:30:49

标签: laravel laravel-5

我正在尝试返回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,或者只能在控制器中完成?

1 个答案:

答案 0 :(得分:0)

将您的最后一行编辑为:

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

  1. 您需要将posts更改为posts()posts是一个Illuminate\Database\Eloquent\Collection对象,没有whereNotIn()方法,posts()将返回Illuminate\Database\Eloquent\Relations\HasMany对象,其中定义了whereNotIn()方法。< / p>

  2. whereNotIn()返回Illuminate\Database\Query\Builder个对象。所以你需要调用get()来获取一个集合。但是,如果您希望flexibilty将其他Builder方法链接到您的remaining_posts()方法,请不要使用get()