0

How do I convert the following to active record style in yii2?

SELECT *
FROM orders
WHERE created_at >= (CURDATE() - INTERVAL 11 MONTH)
ORDER BY id DESC

What I have tried:

switch ($period) {
        case 'y':
            $p = "12 month";
            break;
        case 'm':
            $p = "1 month";
            break;
        case 'w':
            $p = "7 days";
            break;
        case 'd':
            $p = "1 days";
            break;
}

Customers::find()
  ->where('>=', 'created_at', (CURDATE() - INTERVAL $p))
  ->orderBy('id DESC');

But I get:

syntax error, unexpected '$p' (T_VARIABLE)

2 Answers 2

4

insted of pass the string
you could pass the $p as a param

  Customers::find()
    ->where( 'created_at >=(CURDATE() - INTERVAL :p' ), [':p'=>$p])
    ->orderBy('id DESC');
Sign up to request clarification or add additional context in comments.

Comments

3

Yii2 has an Expression class to help with those kinds of things (doc here).

In your case, it'd look something like:

Customers::find()
    ->where(['>=', 'created_at', new \yii\db\Expression('(CURDATE() - INTERVAL ' . $p . ')'))
    ->orderBy('id DESC');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.