yii2 活动记录查找列不相等
我有这个代码来从数据库中查找状态为活动且角色为用户的用户
public static function findByUsername($username)
{
return static::find(['username' => $username, 'status' => static::STATUS_ACTIVE, 'role'=>'user']);
}
我需要找到一个角色不等于“用户”的用户。我该怎么做?
附言:我正在使用 YII2
我有这个代码来从数据库中查找状态为活动且角色为用户的用户
public static function findByUsername($username)
{
return static::find(['username' => $username, 'status' => static::STATUS_ACTIVE, 'role'=>'user']);
}
我需要找到一个角色不等于“用户”的用户。我该怎么做?
附言:我正在使用 YII2
我想提供另一种解决方案,对我来说更优雅。我通常使用这种方法,因为Yii 1当我需要检查不相等的操作。
$models = Book::find()->where('id != :id and type != :type', ['id'=>1, 'type'=>1])->all();
您可以传递自定义 where 子句,如下所示:
andWhere(['!=', 'field', 'value'])
您的最终函数将如下所示:
public static function findByUsername($username)
{
return static::find()
->where([
'username' => $username,
'status' => static::STATUS_ACTIVE
])
->andWhere(['!=', 'role', 'user'])
->all();
}