Join 3 tables (parent, child, grandchild), filtering and sorting from grandchild

Hi, I want to filter and sort data from ‘lineas’ in the ‘camaras’ gridview, being ‘camaras’ the grandchild of ‘lineas’

Here’s my db model

Lineas (parent)
Jaulas (child)
Camaras (grandchild)

I did this in camaras gridview

[//Linea
                'attribute' => 'Linea',
                'format' => 'raw',
                'value' => function ($model) {
                    if ($model->jaula->linea->NOMBRE != null) {
                        return $model->jaula->linea->NOMBRE;
                    }
                }
            ],

But I don’t know how to make the relations for sorting and filtering. If anyone could help me write the CamarasSearch Model it would be great.

The following is the basic.
https://www.yiiframework.com/wiki/653/displaying-sorting-and-filtering-model-relations-on-a-gridview
It deals with one level of relation (parent - child).

For 2 level of relations (parent - child - grandchild), you have to modify it a little. Just a little.

public $grandchild_name;
...
$query->joinWith(['child.grandchild']);
...
$query->andFilterWhere(['like', 'grandchild.name', $this->grandchild_name]);
1 Like

I believe you understood it wrong @softark . I’m trying to read from grandchild to parent. I mean, the oposite way.

So, you say that:

a Linea (parent) has many Jaulas (child), and 
a Jaula (child) has many Camaras(grandchild)

I thought it was that:

a Camara (parent) has a Jaula (child), and
a Jaula (child) has a Linea (grandchild)

The directions are opposite but they are the same.

In CamaraSearch, it would be like the following:

public $linea_NOMBRE;
...
$query->joinWith(['jaula.linea']);
...
$query->andFilterWhere(['like', 'linea.NOMBRE', $this->linea_NOMBRE]);

And for the GridView:

    [  //Linea
        'attribute' => 'linea_NOMBRE',
        'value' => function ($model) {
             if ($model->jaula->linea->NOMBRE != null) {
                 return $model->jaula->linea->NOMBRE;
             }
         }
     ],
1 Like

I did this and it worked

public $linea;
...
$query->joinWith(['jaula.linea']);
...
->andFilterWhere(['like', 'lineas.NOMBRE', $this->linea]);

thanks @softark