拉拉维尔。有关系的模型中的 scope()

时间:2021-03-09 09:36:24

标签: php laravel

用户表

<头>
id 姓名
1 测试1
2 测试2

部门表

<头>
id 姓名
1 部门 1
2 部门 2

departments_user 表

<头>
user_id 部门 ID
1 1
1 1

帖子表

<头>
id 姓名 部门 ID user_id
1 发布 1 1 1
2 帖子 2 2 1

user.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 中创建 Scope

/**
 * @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 Unknown column 'department_user.post_id' in 'where clause'(SQL:从 posts 中选择计数(*)作为聚合存在(从 {{1 }} 内连接 departmentsdepartment_user.departments = id.department_user where department_id.posts = {{1} }.iddepartment_user.post_id = posts.department_id 和 department_user.department_id = 3))

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您需要属于登录用户所有部门的所有帖子。所以要获取登录用户的部门,

$departments = auth()->user()->departments;

然后获取这些部门的所有职位,

$posts = Post::with('departments')
    ->whereIn('department_id', $departments->pluck('id'))
    ->get();