S
S
Sergey Beloventsev2019-07-04 10:26:32
Yii
Sergey Beloventsev, 2019-07-04 10:26:32

Why are not all attributes passed to ActiveRecord queries?

I will make a reservation right away, this is the rest
here is the request

$char=new Expression("*, to_char(".News::tableName().".create_at,'MM') as mouth");
        return News::find()->select($char)->where(['top'=>true])->orderBy(['mouth'=>SORT_ASC])->all();

I get this answer
[
    {
        "id": 1,
        "title": "Title",
        "description": "Title",
        "create_at": "2019-07-04 09:35:19",
        "update_at": "2019-07-04 09:35:19",
        "top": true
    }
]

why is mouth not displayed?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Izmailov, 2019-07-04
@pocifis

This attribute does not exist in the table and it is not explicitly specified in the model, so you do not get it. Either use asArray and get an array instead of models, or explicitly add the needed property to your model.
PS By mouth did you mean month?

D
Dmitry, 2019-07-04
@slo_nik

Good afternoon.
ActiveRecord only works with model attributes.
Use for example yii\db\Connection and get your alias at the end of the attribute array.

query = Yii::$app->db->createCommand("SELECT *, DATE_FORMAT(".Cars::tableName().".car_created_date,'%m') as mouth From `cars` WHERE `status` = 3 LIMIT 2")->queryAll();

G
Gomonov, 2019-07-04
@Gomonov

After the query is executed, the received data is checked against the model schema (ActiveRecord::populateRecord). There is no month field in the model, so it is not returned.
If you replace it with any existing field, you will get the result as a month. create_at,'MM') as mouth

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question