N
N
Nikita Samokhvalov2015-03-19 14:16:33
Yii
Nikita Samokhvalov, 2015-03-19 14:16:33

How to add additional data source in Yii2 models?

Example: There are two models, Text and Tags, inherited from ActiveRecord. There is a REST application that returns data from the Text model, which has the following fields: id, name, desc. I want to add a “dynamic” tags field, which will contain records from the Tags model, so that the REST application, when working with the Text model, would give the following response:

{
     id: 1,
     name: 'First',
     desc: 'Trololo-lol-lollo',
     tags: [ // А вот это уже данные из модели Tags
          id: 1,
          title: 'Hello!'
     ]
},
{
     id: 2,
     …
}

Question: is it possible to somehow describe in Text the logic for obtaining data from Tags, so that the request for data from Tags is made not at each iteration, but once? Tell us how beautiful and profitable to do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
HaruAtari, 2015-03-19
@niksamokhvalov

Yes, you can.

class Test extends ActiveRecord
{
    ...
    public function getTags() 
    {
        return $this->hasMany(Tag::class, ['text_id' => 'id']);
    }
}

In the controller
public function actionIndex()
{
    return Text::find()
        ->andWhere(/* ... */)
        ->with('tags')
        ->all();
}

I wrote the code right here, maybe it was sealed somewhere. But the message is clear. Pull the data with a greedy fetch (specifying the associated model via with()) and it will work as you need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question