View (many) related record

Hi there,

I need to query records from two tables (models) realated as one-to-many; I have these db schema:

Pratica

Id (PK)

Name

Date

[…]

Allegato

Id (PK)

idPratica (Foreing key related to pratica->id)

nomeFile

[…]

Example Data




Pratica

ID    Name     Date

1     name1    date1

2     name2    date2

[...]


Allegato

ID    idPratica     nomeFile

1     1             file1

2     1             file2

3     1             file3

4     2             file4

[...]



How (and where) should I setup to have on my view page, for example, pratica/1 also every record related from Allegato?




PRATICA 1

main data:

ID   1

Name  name1

Date   date1


allegato:

ID  1

nomeFile  file1

ID  2

nomeFile  file2

ID  3

nomeFile  file3




Thank you

Alex

Hi… no one?

Hi,

When I understand your question correct:

You want to give out related data of different models/tables in a single view?

Your relation is already defined between both models?

If not these are the basic steps:

add to your app/model/Pratica.php:




public function getAllegato()

{

    return $this->hasMany(Allegato::className(), ['id' => 'idPratica']);

}



Then you should be able to use lazy loading in your app/views/pratica/view.php

EXAMPLE:




foreach($model->allegato as $allegato){

  echo $allegato->nomeFile."<br>";

}



But everything you need regarding relations & give out related data is well described in the guide.

If you have not read it yet - I strongly suggest to do so:

http://www.yiiframework.com/doc-2.0/guide-README.html

Best Regards

Thank you!

I will read it

Alex