Laravel - 获取与 "whereHas"的嵌套关系

标签 laravel eloquent relationship

我有三个型号 Period , Post , User :

  • periodpostsperiod_posts 上有 M:N 关系
  • postsuserviews 上有 M:N 关系

  • 期间型号:
    class Period extends Model
    {
    
        public $timestamps=false;
    
        public function posts()
        {
            return $this->belongsToMany(Post::class);
        }
    }
    

    岗位型号:
    class Post extends Model
    {
        public function periods()
        {
            return $this->belongsToMany(Period::class);
        }
    
    
        public function views()
        {
            return $this->belongsToMany(User::class, 'views')
                ->withTimestamps();
        }
    }
    

    用户型号:
    class User extends Authenticatable
    {
    use Notifiable;
    
    
    
      public function views()
      {
          return $this->belongsToMany(Post::class, 'views')
              ->withTimestamps();
      }
    }
    

    View 表:
    id user_id post_id
    我需要得到所有 periods与其 posts哪里auth user没看过(按浏览量关系)

    我试图这样做,但没有奏效:
        $period = Period::whereHas('posts.views', function ($users) {
            $users->where('user_id', auth()->Id());
        })->get();
    

    最佳答案

    似乎你的模型有点“凌乱”,你可以用 Eloquent 得到你想要的东西,但你必须将逻辑分成几个部分。

    例子:

    // Get all user seen posts #1
    $seenPosts = Auth::user()->views()->pluck('id');
    
    // Get all user unseen posts with its period inside the collection #2
    $posts = Post::whereNotIn('id',$seenPosts)->with('periods')->get(); 
    

    关于Laravel - 获取与 "whereHas"的嵌套关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56929854/

    相关文章:

    c# - 一堵公共(public)墙和旁边的房间之间有什么样的关系?

    mysql - MySQL 触发器是否激活其他触发器?

    php - 在 Laravel-5 中取消定义方法?

    php - Laravel:对多个值进行多对多过滤

    mysql - 借方余额 - 贷方使用 Eloquent

    sql - 不要在 Laravel Eloquent ORM 中使用准备好的语句?

    MySQL查询单向链接的复杂关系

    php - 从支付网关重定向后清除 Laravel session 和 Auth

    css - 使用 vuejs 和 laravel 消除导航栏和旋转木马之间的差距

    mysql - Laravel 查询过滤器审查与关系