首页 > 解决方案 > Laravel - 使用“whereHas”获取嵌套关系

问题描述

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

时期型号:

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();
  }
}

视图表:

id user_id post_id

我需要了解所有未见过periodsposts地方(通过视图关系)auth user

我试图这样做,但没有奏效:

    $period = Period::whereHas('posts.views', function ($users) {
        $users->where('user_id', auth()->Id());
    })->get();

标签: laraveleloquentrelationship

解决方案


似乎你的模型有点“混乱”,你可以用 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(); 

推荐阅读