Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 relational data from 3rd level

A little bit connecting to my previous question:

I have following tables/models: enter image description here

I've managed to join all tables for actionIndex, but I would like to implement now the same thing for actionView, but it seems find() and findOne() doesn't work the same. Joins don't work with findModel($id)

I don't really have clue, can you please point me to the right direction? In fact I need only to show related data of model A in model BCD view, and I'm quite sure there is a simple way doing it, but I can't find anything, I don't even really know what to look for. Becuse the problem is, with normal relationships I can only reach out to table B, so maximum 2 levels. I've tried to create a relationship that reaches out to 3rd level but it's not working. Thanks.

like image 278
user2511599 Avatar asked Jul 05 '15 18:07

user2511599


Video Answer


1 Answers

You do not have to define multi levels relations.

If you have to do this for 1 record in BCD you can just access it with

$BCDmodel->BC->B->A->attribute

of course use the names of the relations that you have defined.

This will also work when showing this info in a table BUT ... it is quite inefficient. For every row you show you will get a lot of queries so you should change the query to make it more efficient.

$query = BCD::find()->with(['BC', 'BC.B', 'BC.B.A']).....

This will join everything together and make the query a much better one, when you do need to show the data you can still use

$BCDmodel->BC->B->A->attribute

Just make sure that your BCD model has a relation to BC named BC, your BC model has a relation to B called B, your B model has a relation to A called A and the above should work.

like image 99
Mihai P. Avatar answered Nov 10 '22 20:11

Mihai P.