使用对象过滤查询集

时间:2015-08-05 11:49:23

标签: database laravel laravel-5 eloquent relationship

目前我有

foreach($this->friends as $friend) {
    $user_ids[] = $friend->id;
}

$posts = Post::whereIn("user_id", $user_ids)->orderBy("date_published", "desc")->paginate(15);

似乎还可以,但是数组的创建有点奇怪。有没有办法可以通过User对象自己进行过滤?例如

Post::whereIn("user", $this->friends)

其中$this->friends将是

public function friends() {
    return $this->belongsToMany("App\User", "friends_users", "user_id", "friend_id");
}

1 个答案:

答案 0 :(得分:1)

$this->friends是一个Collection对象,它有lists方法,可以从列创建数组,或者从2列创建关联数组。这是你如何使用它。

$posts = Post::whereIn("user_id", $this->friends->lists('id'))->orderBy("date_published", "desc")->paginate(15);
相关问题