【发布时间】:2019-11-17 16:04:23
【问题描述】:
我有三个模型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();
}
}
查看表:
id
user_id
post_id
我需要获取所有periods 及其posts,其中auth user 没有看到(通过查看关系)
我尝试这样做,但没有奏效:
$period = Period::whereHas('posts.views', function ($users) {
$users->where('user_id', auth()->Id());
})->get();
【问题讨论】:
-
所以你必须为已验证的用户获取所有时期及其看不见的帖子?
-
views 表是否只包含看到的帖子?
-
views 表包含
post_id和user_id...换句话说,post与使用user表的user有 m:n 关系
标签: laravel eloquent relationship