我有三个型号 Period
, Post
, User
:
period
和 posts
在 period_posts
上有 M:N 关系posts
和 user
在 views
上有 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/