laravel - Laravel - 使用“whereHas”获取嵌套关系
问题描述
我有三个模型Period
, Post
, User
:
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);
}
}
岗位型号:
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();
解决方案
似乎你的模型有点“混乱”,你可以用 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();
推荐阅读
- discord - 如何让不和谐的机器人发送邀请?
- express - 我正在尝试通过 heroku 部署 MEAN 应用程序,但我陷入了困境
- javascript - 对话流返回一个空响应,尽管有数据
- kotlin - 错误:Kotlin 中的重载分辨率歧义
- angular - 角度文件上传不适用于 formData
- python-3.x - Selenium webdriver既不打开Chrome也不打开Firefox浏览器,我在pycharm中下载了chromedriver、geckodriver
- javascript - onClick 函数或模式的限制?
- azure - Azure CDN 端点 - 无法添加响应标头
- mysql - 是否值得在 Mysql 上启用统计信息
- sas - SAS 标记包含最大值的每一行