yii2 active record find column not equal

前端 未结 5 1740
轻奢々
轻奢々 2021-02-18 13:41

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([\'userna         


        
相关标签:
5条回答
  • 2021-02-18 13:59

    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'"));
    }
    
    0 讨论(0)
  • 2021-02-18 14:02

    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();
    }
    
    0 讨论(0)
  • 2021-02-18 14:10

    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.

    $models = Book::find()->where('id != :id and type != :type', ['id'=>1, 'type'=>1])->all();
    
    0 讨论(0)
  • 2021-02-18 14:11

    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),
            ));
    
    0 讨论(0)
  • 2021-02-18 14:13

    You can pass custom where clause like this:

    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();
    }
    
    0 讨论(0)
提交回复
热议问题