首页 > 解决方案 > 拉拉维尔。具有关系的模型中的范围()

问题描述

用户表

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 postswhere exists (select * from departmentsinner join department_useron departments. id= department_user. department_idwhere posts. id= department_user. post_idand department_user. department_id= posts.department_id 和department_user. user_id= 3))

标签: phplaravel

解决方案


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

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

然后得到那些部门的所有职位,

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

推荐阅读