php - 拉拉维尔。具有关系的模型中的范围()
问题描述
用户表
ID | 姓名 |
---|---|
1 | 测试1 |
2 | 测试2 |
部门表
ID | 姓名 |
---|---|
1 | 部门 1 |
2 | 部门 2 |
department_user 表
用户身份 | 部门编号 |
---|---|
1 | 1 |
1 | 1 |
帖子表
ID | 姓名 | 部门编号 | 用户身份 |
---|---|---|---|
1 | 帖子 1 | 1 | 1 |
2 | 帖子 2 | 2 | 1 |
用户.php
class user extends Model{
/**
* @return mixed
*/
public function departments(){
return $this->belongsToMany(Department::class);
}
}
部门.php
class Department extends Model
{
/**
* @return mixed
*/
public function users(){
return $this->belongsToMany(User::class);
}
}
post.php
class Post extends Model
{
/**
* @return mixed
*/
public function users()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
/**
* @return mixed
*/
public function departments()
{
return $this->belongsTo(Department::class,'department_id', 'id');
}
}
我需要从部门用户那里获取所有帖子
我在 post.php 中创建范围
/**
* @param $query
*
* @return mixed
*/
public function scopePostsUser($query)
{
$query->whereHas('departments', function ($user){
$user->where('department_user.department_id', 'posts.department_id');
$user->where('department_user.user_id', auth()->id());
});
}
我的查询
Post::with('departments')->PostsUser();
错误
SQLSTATE [42S22]:未找到列:1054 'where 子句'中的未知列'department_user.post_id'(SQL:select count(*) as aggregate from
posts
where exists (select * fromdepartments
inner joindepartment_user
ondepartments
.id
=department_user
.department_id
whereposts
.id
=department_user
.post_id
anddepartment_user
.department_id
= posts.department_id 和department_user
.user_id
= 3))
解决方案
如果我理解正确,您想要属于登录用户所有部门的所有帖子。所以要获取登录用户的部门,
$departments = auth()->user()->departments;
然后得到那些部门的所有职位,
$posts = Post::with('departments')
->whereIn('department_id', $departments->pluck('id'))
->get();
推荐阅读
- java - 是否可以禁用 Spring Cloud Stream Starter 应用程序的安全性?
- orm - 休眠搜索子实体
- wordpress - Wordpress ?ver=### 未加载最新的子主题样式表
- chef-infra - 厨师选项卡自动转换为空格
- r - 如何一次调用函数的特定输出
- windows - 在 Windows 上安装 HDF5 的分步说明
- ios - 如何在 iOS 的集合视图中为内容偏移设置动画?
- angular - 在 Angular 6 和 Phonegap 上推送通知
- php - 上传文件时的url,图片不上传
- h2o - H2O 等效于 H2O python 中的 allStringVecToCategorical() 和 score() api