V
V
Viktor Yanyshev2018-02-17 13:12:09
Yii
Viktor Yanyshev, 2018-02-17 13:12:09

How to create object property by alias in yii2 when fetching via AR?

There is such a cast on the sample:

News::find()
            ->select(["DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y') as year, DATE_FORMAT(FROM_UNIXTIME(created_at), '%m') as month, COUNT(created_at) as count, created_at"])
            ->where(['status' => News::STATUS_ACTIVE]) //"DATE_FORMAT(FROM_UNIXTIME(created_at), '%Y')" => $year
            ->groupBy('year, month')
            ->orderBy(['year' => SORT_DESC, 'month' => SORT_DESC])
            ->all();

Return an array of objects:
{array} [2]
 0 = {app\models\News} [9]
 1 = {app\models\News} [9]
.....
0 = {app\models\News} [9]
 *yii\db\BaseActiveRecord*_attributes = {array} [1]
    created_at = 1516742158

How can you create an object property in an object by alias from select without resorting to createCommand?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2018-02-19
@qonand

If I understand the problem correctly, then it is enough just to declare the corresponding fields in the class, for example:

class News extends ActiveRecord
{
     public $year;

     public $month;

     public $count;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question