如何从用户的订阅中获得所有帖子
问题描述:
在我的应用程序中,我已经通过名为subscriptions
的数据透视表建立了一个用户模型,该模型可以具有订阅者和订阅。如何从用户的订阅中获得所有帖子
public function subscribers()
{
return $this->belongsToMany('Forum\User', 'subscriptions', 'subscription_id', 'subscriber_id');
}
public function subscriptions()
{
return $this->belongsToMany('Forum\User', 'subscriptions', 'subscriber_id', 'subscription_id');
}
我的问题是,我应该用什么关系从用户的订阅中获得分页Post模型列表(属于用户)?
答
可以使用whereHas
方法过滤器的基础上的关系。假设你的Post
模型定义的user
关系,你的代码看起来是这样的:
// target user
$user = \App\User::first();
$userId = $user->id;
// get all of the posts that belong to users that have your target user as a subscriber
\App\Post::whereHas('user.subscribers', function ($query) use ($userId) {
return $query->where('id', $userId);
})->paginate(10);
您可以在文档中阅读更多关于querying relationship existence。
谢谢!完美的作品。 – Biskotaki