输出值不等于 yii2 中的某些值

Outputting values not equal to certain values in yii2

我想输出不等于特定值的变量,但它 return 是

的错误
Failed to prepare SQL: SELECT * FROM `tblsuunit` WHERE `unitid` != :qp0

有两个模型,第一个模型正在获取 ID 数组

public function actionSunits($id){
    $unitslocation = new Unitslocation();
    $id2 = Unitslocation::find()->where(['officelocationid'=>$id])->all();
      foreach( $id2 as $ids){
      print_r($ids['unitid']."<br>");
      }
    }

这会将 id 输出为

8
9
11
12
13
14
16

然后我想获取 id 并比较另一个模型(单位模型)并获得与上面不相似的 id 值然后输出

所以我添加了

 $idall = Units::find()->where(['!=', 'unitid', $ids])->all();

所以整个控制器动作变成了

public function actionSunits($id){
    $unitslocation = new Unitslocation();
    $id2 = Unitslocation::find()->where(['officelocationid'=>$id])->all(); 


   foreach( $id2 as $ids){
         $idall = Units::find()->where(['!=', 'unitid', $ids])->all();

     }
     var_dump($idall);

}

这是单位模型table:

如果它正常工作,它应该 return 7 和 10

可能有什么问题..

试试:

$idall = Units::find()->where(['not in','unitid',$ids])->all();

信息https://github.com/yiisoft/yii2/blob/master/docs/guide/db-query-builder.md

operand 1 should be a column or DB expression. Operand 2 can be either an array or a Query object.

您应该修复您的代码并简单地使用 not in 条件,例如:

// $uls will be an array of Unitslocation objects
$uls = Unitslocation::find()->where(['officelocationid'=>$id])->all(); 

// $uids will contain the unitids
$uids = \yii\helpers\ArrayHelper::getColumn($uls, 'unitid');

// then simply use a not in condition
$units = Units::find()->where(['not in', 'unitid', $uids])->all();

$idall = \yii\helpers\ArrayHelper::getColumn($units, 'unitid');

详细了解 ActiveQuery::where() and ArrayHelper::getColumn()