Laravel - 获取与“whereHas”的嵌套关系

Mor*_*far 5 relationship laravel eloquent

我有三个型号Period,,PostUser

  • period并且posts有 M:N 关系period_posts

  • posts并且user有 M:N 关系views

时期型号:

class Period extends Model
{

    public $timestamps=false;

    public function posts()
    {
        return $this->belongsToMany(Post::class);
    }
}
Run Code Online (Sandbox Code Playgroud)

帖子型号:

class Post extends Model
{
    public function periods()
    {
        return $this->belongsToMany(Period::class);
    }


    public function views()
    {
        return $this->belongsToMany(User::class, 'views')
            ->withTimestamps();
    }
}
Run Code Online (Sandbox Code Playgroud)

用户型号:

class User extends Authenticatable
{
use Notifiable;



  public function views()
  {
      return $this->belongsToMany(Post::class, 'views')
          ->withTimestamps();
  }
}
Run Code Online (Sandbox Code Playgroud)

视图表:

id user_id post_id

我需要得到所有没有见过的地方periods(通过视图关系)postsauth user

我尝试这样做,但没有成功:

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

小智 4

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