tlerbao
V2EX  ›  问与答

ThinkPHP 多对多关联如何条件查询?

  •  
  •   tlerbao · May 23, 2021 · 1433 views
    This topic created in 1842 days ago, the information mentioned may be changed or developed.

    三张表(用户表、部门表、中间表:user_has_departments ) 用户可以隶属多个部门,所以定义了多对多关系。 中间表:id,user_id,department_id

    关联关系

        // 用户模型下定义
        public function departments()
        {
            return $this->belongsToMany(Department::class, 'user_has_departments', 'department_id', 'user_id');
        }
        
        // 部门模型相对定义
        public function user()
        {
            return $this->belongsToMany(Users::class,'user_has_departments', 'user_id', 'department_id');
        }
    

    需求

    根据传入的部门 ID 集合,查询出所属用户列表。 传入的部门 ID 如[2,5,6,7],所以是一次查询多个部门,ThinkPHP 的多对多好像不支持 hasWhere,所以不知道怎么查询,请大神解答。

    我目前的做法(实现最终需求但感觉 Low,所以来提问)

        // 直接 Db 查询中间表获得 user_id 集合
        $userIds = Db::name('user_has_departments')
                ->whereIn('department_id',[2,5,6,7])
                ->column('user_id');
        // 然后再从 user 表 in 查询用户(我这个是写在搜索器里的,所以返回的是$query )
        return $query->whereIn('id', $userIds);
    
    3 replies    2021-05-23 13:08:25 +08:00
    2kCS5c0b0ITXE5k2
        1
    2kCS5c0b0ITXE5k2  
       May 23, 2021
    连表查不就好了. 既然知道了.部门 ID
    tlerbao
        2
    tlerbao  
    OP
       May 23, 2021
    @emeab join? 我就想看看关联模型的关联查询有没有什么直接的方法
    ferock
        3
    ferock  
    PRO
       May 23, 2021 via iPhone
    这种时候,拼接的 sql,越复杂越难控制,直接写 sql 不更好吗?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5499 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 08:32 · PVG 16:32 · LAX 01:32 · JFK 04:32
    ♥ Do have faith in what you're doing.