Find with foreign key

Hi people,

I’m using the find() function, to get a model from a table.

Like this:


$mveiculos = Veiculos::model()->findAllByAttributes(array('cod_anuncio' => (int)$cod_anuncio));

Descriptions of my tables:

Veiculos

cod_modelo FK

cod_veiculo

cod_anuncio

Modelos

cod_modelo

desc_modelo

When i get a Veiculos model with the function findAllByAttributes(), it return the model, with cod_modelo.

I wanna know if exists some way to include the table "Modelos" in the query, usinh this function.

I already put the table Modelos in the relations() of model Veiculos.

Can somebody help me?

big hugs

If the relation name for Modelos is "modelo", then the query should look like:


$mveiculos = Veiculos::model()->with('modelo')->findAllByAttributes(array('cod_anuncio' => (int)$cod_anuncio));

Then you can get related models this way:




foreach ($mveiculos as $obj)

    echo $obj->modelo->desc_modelo;



Note, you can do that without using “with(‘modelo’)” when getting Veiculos models, but in this case all related models will be lazy-loaded. Please, read the Guide: http://www.yiiframework.com/doc/guide/1.1/en/database.arr#performing-relational-query

Wow. This really resolve my problem.

Thank you very much andy.

Bye