简体   繁体   中英

how to get data between two dates of Last month in YII?

I want to get data of the last month, i am using the below code to do it, but it is not working correctly for me:

Here is my code:

public function getLastMonth($user_id)
{       
    $criteria=new CDbCriteria;

    $criteria->condition = 'leave_from_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)';
    $criteria->condition = 'leave_to_date <= DATE_SUB(CURDATE(), INTERVAL 1 DAY)';
    $criteria->condition = "user_id = $user_id";
    $data = Leaves::model()->findAll($criteria);
    $lastMonthR = 0;
    foreach($data as $lastMonth)
     {
         $lastMonthR += $lastMonth->total_leaves_hours;
     }      
    //return lastMonthR CHtml::encode($lastMonthR);
    return $lastMonthR;
}

I want to get the result equivalent to the results of following query that is in MYSQL:

SELECT *,sum(total_leaves_hours) FROM tbl_leaves
WHERE leave_from_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) AND 
leave_to_date <= DATE_SUB(CURDATE(), INTERVAL 1 DAY) ;

When i run the code(shown above) of YII, it shows me all the data of the table, please help me i am new to YII. thanks in advance.

When you assign a value for condition for the second time you write over the first condition. Combine the two into a single condition. You should also use prepared statements instead of string interpolation:

$criteria->condition = 'leave_from_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)
      AND leave_to_date <= DATE_SUB(CURDATE(), INTERVAL 1 DAY
      AND user_id = :id';

$data = Leaves::model()->findAll($criteria, array (':id'=>$user_id));

You wrote $criteria->condition = ... three times. That assigns the last value and discards the rest. Joni's answer gives a simple solution.

However, after looking closer at your logic, it can actually be replaced with a simpler SUM query, if you do not use any other data from the query. The sample query you gave selects more data, but the function you wrote does not use it - it's not clear if you actually need the records themselves.

public function getLastMonth($user_id) {
    $cmd = Yii::app()->db->createCommand()
      ->select('SUM(total_leaves_hours)')
      ->from(Leaves::model()->tableName())
      ->andWhere('leave_from_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)')
      ->andWhere('leave_to_date <= DATE_SUB(CURDATE(), INTERVAL 1 DAY)')
      ->andWhere('user_id = :user_id', array(
        ':user_id' => $user_id,
      ))
    ;

    return $cmd->queryScalar();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM