使用对象过滤查询集
Filtering queryset with objects
目前我有
foreach($this->friends as $friend) {
$user_ids[] = $friend->id;
}
$posts = Post::whereIn("user_id", $user_ids)->orderBy("date_published", "desc")->paginate(15);
看起来不错,工作正常,但数组的创建有点奇怪。有没有一种方法可以按用户对象本身进行过滤?例如
Post::whereIn("user", $this->friends)
其中 $this->friends
将是
public function friends() {
return $this->belongsToMany("App\User", "friends_users", "user_id", "friend_id");
}
$this->friends
是一个 Collection
对象,它有一个 lists
方法,它从一列创建一个数组,或者从两列创建一个关联数组。下面是您将如何使用它。
$posts = Post::whereIn("user_id", $this->friends->lists('id'))->orderBy("date_published", "desc")->paginate(15);
目前我有
foreach($this->friends as $friend) {
$user_ids[] = $friend->id;
}
$posts = Post::whereIn("user_id", $user_ids)->orderBy("date_published", "desc")->paginate(15);
看起来不错,工作正常,但数组的创建有点奇怪。有没有一种方法可以按用户对象本身进行过滤?例如
Post::whereIn("user", $this->friends)
其中 $this->friends
将是
public function friends() {
return $this->belongsToMany("App\User", "friends_users", "user_id", "friend_id");
}
$this->friends
是一个 Collection
对象,它有一个 lists
方法,它从一列创建一个数组,或者从两列创建一个关联数组。下面是您将如何使用它。
$posts = Post::whereIn("user_id", $this->friends->lists('id'))->orderBy("date_published", "desc")->paginate(15);