Answer the question
In order to leave comments, you need to log in
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,
…
}
Answer the question
In order to leave comments, you need to log in
Yes, you can.
class Test extends ActiveRecord
{
...
public function getTags()
{
return $this->hasMany(Tag::class, ['text_id' => 'id']);
}
}
public function actionIndex()
{
return Text::find()
->andWhere(/* ... */)
->with('tags')
->all();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question