douchuoliu4422 2016-11-20 18:23
浏览 34
已采纳

如何从用户的订阅中获取所有帖子

In my application, I have setup a User model that can have subscribers and subscriptions through a pivot table called 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');
}

My question is, what relationship should I use to get a list of paginated Post models (belong to a User) from the User's subscriptions?

  • 写回答

2条回答 默认 最新

  • dongxie3701 2016-11-21 03:07
    关注

    You can use the whereHas method to filter based on relationships. Assuming your Post model has a user relationship defined, your code would look something like:

    // 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);
    

    You can read more about querying relationship existence in the documentation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了