Getting data between 3 tables in yii, cgridview


I'm using the yii framework and I need the information that is in the table route. I am searching for this information from the vehicle table. There is a third table called Equipment In vehicle I have a foreign key called equipo_fk On route I have a foreign key for equipment (equipo_fk) Vehicle Relation:

'cliente' => array(self::BELONGS_TO, 'Cliente', 'Cliente'),
'equipamento0' => array(self::BELONGS_TO, 'Equipamento', 'equipamento'),
'motorista0' => array(self::BELONGS_TO, 'Motorista', 'motorista'),

Doubt is how from vehicle can I get the data that is in the route table. And use this information with cgridview.

asked by anonymous 23.10.2014 / 07:17

2 answers


So I understand you want to put in CGridView information from a third table. From what I noticed you have a N to N relation between Veículos and Rotas .

According to the Framework wiki reference you will have to:

1º) In the Vehicle model you should add a variable:

public $rotas_search;

2º) Change the rules() function to add the new field in the "Safe on Search" list.

  public function rules() {
    return array(
      array( '........,rotas_search', 'safe', 'on'=>'search' ),

3rd) Now you need to add the field in your method search()

public function search() {
  $criteria = new CDbCriteria;
  $criteria->with = array( 'equipamento0' );
  //Onde rotas é a relação entre a tabela equipamento e a tabela rota
  //rotas[0] indica que vai pegar a primeira rota da lista.
  $criteria->compare( 'equipamento0.rotas[0].id', $this->rotas_search, true );

4º) Then at the end of the search method you modify the return by adding your new field.

return new CActiveDataProvider( $this, array(
                'desc'=>'equipamento0.rotas[0].id DESC',

5º) Finally in your CGridView , add the column.

$this->widget('zii.widgets.grid.CGridView', array(
        array( 'name'=>'rotas_search', 'value'=>'$data->equipamento0->rotas[0]->id' ),

Note that it only works for displaying a route value. You can find more information and other approaches to this problem here (English). And here (English) you will have another approach to how to put more than one field in the view (I found it a bit tricky, but if it works and does not cause problems, then it's a solution).

23.10.2014 / 15:33

It would be something like this:

$equipamentos = $model->Equipamento;

foreach($equipamentos as $equipamento) {
    echo 'codigo_equipamento:'.$equipamento->id.'<br/>';
    echo '<hr />';


so you can do it for other related tables.

23.10.2014 / 14:20