U
U
urfinjazz2015-05-30 11:08:49
Yii
urfinjazz, 2015-05-30 11:08:49

How to work with linked tables in Yii2 using ActiveRecord?

Hello!
I am learning the Yii2 framework, I got to work with the database.
I generate CRUD using gii, the findModel function appears in the controller, in which there is such a request:
$model = Pages::findOne($id)
This line returns data from the table by ID.
I need to get data from a related table, I do this:

$model = Pages::find()
                ->leftJoin('content', '`content`.`page_id` = `pages`.`id`')
                ->where(['content.page_id' => $id])
                ->all()

But in this case, the data is selected only from the first table (you need to get the fields from the second one as well).
In this regard, 2 questions arise:
1. Is accessing the database in the controller generally normal? (I always thought that this is the prerogative of the model, but since it is implemented at the framework level? In general, I think I should transfer the logic I wrote to the model)
2. How to display the fields of the linked table? Somewhere you need to initially indicate that they exist? Help me to understand!
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mishutka2000, 2015-05-30
@urfinjazz

Create an association with the getContents() model. After that, you can access the attributes of the associated table through the relationship: $model->getContents()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question