繁体   English   中英

YIi2获取未包含在另一个表中的记录

[英]YIi2 get records not contained in another table

我想检索一个表中未包含的记录

我有两张桌子

tb_users having columns
   id(primary key) 
   username, 
   firstname, 

2. tbl_paychecks
     id(primary key)
     user_id(foreignkey)
     amount
     created_at
     ...

现在,我想检索所有没有薪水的用户,即其ID不在tbl_paychecks中的所有tbl_users

所以在我的用户模型中

public function getNOPaychecks()
  {
    return self::find()
      ->leftJoin('tbl_paychecks','`tbl_paychecks`.`user_id` != `tbl_user`.`id`')
       ->where(['tbl_paycheks.user_id'=>null])
       ->all();
   }

但是上面仍然返回错误

unknown column tbl_paycheks.user_id in 'where clause

我要去哪里错了?

您在表名称中输入了类型tbl_ paycheks而不是tbl_paychecks ,对于null,您可以使用

public function getNOPaychecks()
{
  return self::find()
    ->leftJoin('tbl_paychecks','`tbl_paychecks`.`user_id` != `tbl_user`.`id`')
     ->where(['is', 'tbl_paychecks.user_id', null])
     ->all();
 }

不确定代码为何无法正常工作。尝试作为两个查询来执行。

public function getNOPaychecks()
{
   $paycheckUsers = ArrayHelper::getColumn(PayCheckModelClassName::find()->select(['user_id'])->asArray()->all(),'user_id');
   return self::find()
      ->where(['NOT IN','id',$paycheckUsers])
      ->all();
}

您可以在查询中使用“存在”或“不存在”运算符,请尝试以下操作:

 public function getNOPaychecks()
  {
        $subQuery = (new Query())->select('*')->from('tbl_paycheks' . ' t2')->where(
            't2.user_id=t2.user_id'
        );

    return self::find()
      ->alias('t1')
       ->where(['not exists',$subQuery])
       ->all();
   }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM