Surely, I can Yii::$app->db->createCommand($sql)->query()
,
but what if I wanna use a ActiveRecord::find()->where($conditions)
to do this job ?
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.
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.
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.
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.
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:
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With