how to used IN & Between Clause in YII ACtive Record?

后端 未结 7 1734
轻奢々
轻奢々 2021-02-14 10:15

I want write a Following Query in Active record .

SELECT *
FROM `User`
WHERE `UserId`
IN ( 6, 7, 8, 9 ) ;

Thanks

相关标签:
7条回答
  • 2021-02-14 10:30

    Either you can use addInCondition or you can also use compare method.

     $criteria = new CDbCriteria();
     $criteria->compare('UserId',array(6,7,8,9));
     $userDataObj = User::model()->findAll($criteria);
    
    0 讨论(0)
  • 2021-02-14 10:33

    You might use both IN and BETWEEN statements thru CDbCriteria:

    $criteria = new CDbCriteria();
    $criteria->addInCondition("id", array(6,7,8,9));
    $criteria->addBetweenCondition('id', '10', '20', 'OR');
    $result = User::model()->findAll($criteria);
    

    this will result in SQL query like this:

    SELECT *
    FROM `User`
    WHERE `id`
    IN ( 6, 7, 8, 9 )
    OR `id` BETWEEN 10 AND 20
    

    Note the 4-th paramenter OR in addBetweenCondition() method; missing it, the default AND will be applied to concatenate that condition to the rest of WHERE-query.

    P.S. Strictly speaking those addBetweenCondition() and addInCondition() methods should be added to an existing condition. So, you might need to set first a criteria's initial condition like this:

    $criteria->condition = '1=1';
    
    0 讨论(0)
  • 2021-02-14 10:37

    I still using this way:

    public function getInterval( $data_start, $data_stop ){
      $criteria = new CDbCriteria;
      $criteria->condition = "date  >= '$data_start' AND date <= '$data_stop'";
      return $criteria;
    }
    $model = Object::model()->findAll(getInterval('2014-06-01','2014-06-30');
    
    0 讨论(0)
  • 2021-02-14 10:39

    You can put your array as a value for a specific attribute, like this (no tested):

    $model=new User();
    $result=$model->findAllByAttributes(array('UserId'=>array(6,7,8,9)));
    
    0 讨论(0)
  • 2021-02-14 10:44

    You can use CDbCriteria statement:

    $criteria = new CDbCriteria();
    $criteria->addInCondition('userId', array(6,7,8,9));
    $result = User::model()->findAll($criteria);
    
    0 讨论(0)
  • 2021-02-14 10:44

    There is an function called findAllBySql in yii to run sql query and get the outputs.

    $sql="SELECT * FROM `User` WHERE `UserId` IN ( 6, 7, 8, 9 )";//Your Sql query
    $value=User::model()->findAllBySql($sql);// "User" is the model belongs to the table 'User'
    

    The "$value" will return the result in a array. To get the values you can use the following method.

    foreach($value as $val){
       echo $val->UserId;
    }
    

    (or)

    var index=0;
    echo $val[$index]->UserId;
    
    0 讨论(0)
提交回复
热议问题