Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to build query like `select ... where id % 2 = 1` using Yii 2 ?

Surely, I can Yii::$app->db->createCommand($sql)->query(), but what if I wanna use a ActiveRecord::find()->where($conditions) to do this job ?

like image 717
haoliang Avatar asked Aug 19 '15 06:08

haoliang


People also ask

How to write SQL query in Yii2?

Call yii\db\QueryBuilder to generate a SQL statement based on the current construct of yii\db\Query; Create a yii\db\Command object with the generated SQL statement; Call a query method (e.g. queryAll()) of yii\db\Command to execute the SQL statement and retrieve the data.

What is Query Builder in Yii2?

The Yii Query Builder provides an object-oriented way of writing SQL statements. It allows developers to use class methods and properties to specify individual parts of a SQL statement.

Is null in Yii2 query?

Yii2 will use "IS NULL" if the $values === null , but in case the value is supplied as an array, and one of those array elements is null, it will not get any special treatment, resulting in the query never matching any records with NULL value.

How to delete Record in Yii2?

To delete a single row of data, first retrieve the Active Record instance corresponding to that row and then call the yii\db\ActiveRecord::delete() method. $customer = Customer::findOne(123); $customer->delete(); You can call yii\db\ActiveRecord::deleteAll() to delete multiple or all rows of data.


2 Answers

Here is one of the options with using yii\db\Expression:

use yii\db\Expression;

...

$models = Customer::find()
    ->select(['id', 'name', ...])
    ->where(new Expression('id % 2 = 1')])
    ->all();

It's definetely better than raw sql and ['%2=', 'id', 1] because it follows the order and more readable in my opinion.

['%2=', 'id', 1] also is not suitable here because %2= is not actually an operator like not in or like for example, so operator, value and = sign are kind of mixed together.

Official docs:

  • yii\db\Expression

Update: I asked samdark, one of the main framework contributors in official Gitter chat and he said that the right way to do it is using yii\db\Expression.

like image 156
arogachev Avatar answered Oct 31 '22 04:10

arogachev


You can achieve this using Active Query too. This may help.

$customers = Customer::find()
    ->select(['id', 'name', ...])
    ->where('id % 2 = 1')
    ->all();

or

$customers = Customer::find()
    ->select(['id', 'name', ...])
    ->where(['% 2 =', 'id', 1])
    ->all();

Reference.

like image 24
ankitr Avatar answered Oct 31 '22 03:10

ankitr