php yii2活动记录查找列不相等
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22962869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
yii2 active record find column not equal
提问by Sarvar Nishonboev
I have this code to find a user from db which status is active and role is user
我有此代码可以从数据库中查找状态为活动且角色为用户的用户
public static function findByUsername($username)
{
return static::find(['username' => $username, 'status' => static::STATUS_ACTIVE, 'role'=>'user']);
}
I need to find a user that role is not equal to "user". How can I do this?
我需要找到一个角色不等于“用户”的用户。我怎样才能做到这一点?
P.S: I'm using YII2
PS:我正在使用 YII2
回答by Alex
I want to offer another solution, it's more elegant for me. I usually use this approach since Yii 1 when i need check not equal operation.
我想提供另一种解决方案,它对我来说更优雅。当我需要检查不相等操作时,我通常从 Yii 1 开始使用这种方法。
$models = Book::find()->where('id != :id and type != :type', ['id'=>1, 'type'=>1])->all();
回答by Stanimir Stoyanov
You can pass custom where clause like this:
您可以像这样传递自定义 where 子句:
andWhere(['!=', 'field', 'value'])
Your final function will look like:
您的最终函数将如下所示:
public static function findByUsername($username)
{
return static::find()
->where([
'username' => $username,
'status' => static::STATUS_ACTIVE
])
->andWhere(['!=', 'role', 'user'])
->all();
}
回答by Sarvar Nishonboev
Ok, i've done by this way:
好的,我已经这样做了:
public static function findByUsername($username)
{
$sql="select * from tbl_user where username=:uname and status=:st and role != 'user'";
return static::findBySql($sql,[":uname"=>$username,":st"=>static::STATUS_ACTIVE])->one();
}
回答by Manoj Kumar
you can try this one . just an example
你可以试试这个。只是一个例子
$existEmail = Users::model()->findByAttributes(
array('email'=>$this->email),
array(
'condition'=>'user_id!=:id',
'params'=>array('id'=>$this->user_id),
));
回答by Wit Wikky
You can try:
你可以试试:
public static function findByUsername($username)
{
$criteria = new CDbCriteria;
$criteria->addCondition("username != 'username'");
$criteria->addCondition("role != 'user'");
$result = User::model()->find($criteria);
return $result;
}
Or:
或者:
public static function findByUsername($username)
{
$result=Users::model()->findByAttributes(array('condition'=>"role != 'user',username = '$username'"));
}