P
P
Padre2017-07-15 09:35:15
Yii
Padre, 2017-07-15 09:35:15

How to build ActiveRecord queries in Yii2?

I read the manual, both this one and in the tutorial on github, but I still can’t figure out the technique for compiling queries on ActiveRecord
. For example, the query that was built into Yii2 right after installation works:

$countries = $query->orderBy('name')
->offset($pagination->offset)
->limit($pagination->limit)
->all();

Remove the indent from it and limit - does not work
$countries = $query->orderBy('name')
->all();

Mistake:
PHP Warning - yii\base\ErrorException
htmlspecialchars() expects parameter 1 to be string, array given

A simple count query works:
$countries = $query->where(['country.code' => 'AU'])->count();

Let's try to get data:
$countries = $query->where(['country.population' > 4444444])->all();

Mistake:
Invalid Parameter - yii\base\InvalidParamException
Operator ''requires two operands.

Ok, let's rewrite and take out the comparison operator:
$countries = $query->where(['>', 'country.population', 4444444])->all();

The error says that I am passing the array (where is the array here?) to where the string should be:
PHP Warning – yii\base\ErrorException
htmlspecialchars() expects parameter 1 to be string, array given

In general, is there a good manual on this topic? Interested not in these specific requests, but in the principle of construction?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Bukharev, 2017-07-15
@evgenybuckharev

It's a Query Builder, not an ActiveRecord.
Get yourself an IDE like PhpStorm, and drop into the method on click on it, and see what arguments it takes and how it uses them. And so the documentation clearly enough describes how to use this functionality.
You can also use:

$countries = $query->orderBy('name')
->offset($pagination->offset)
->limit($pagination->limit)
->createCommand()->rawSql;

In order to understand what kind of sql query is compiled and sent to the database

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question