目前我有
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");
}
答案 0 :(得分:1)
$this->friends
是一个Collection
对象,它有lists
方法,可以从列创建数组,或者从2列创建关联数组。这是你如何使用它。
$posts = Post::whereIn("user_id", $this->friends->lists('id'))->orderBy("date_published", "desc")->paginate(15);