Daunio Daunio - 2 months ago 31
PHP Question

Yii2 - How to filter a related model via a pivot table

This is my first question, I hope someone can help me.

How to filter a related model (via a pivot table) ?

I have model A, model A_B, and model B. A_B is the pivot (id, a_id, b_id)

I display in a GridView all A instances and I collect easily related B model. But completely unaware how to filter those B models.

Answer

You can use multi relation by using hasMany relation and filter as below.

Model A file

namespace app\models;

use Yii;

class A extends yii\db\ActiveRecord 
{
....

function getRelated(){
return $this->hasMany(B::className(), ['id' => 'b_id'])
->viaTable(A_B::tableName(), ['a_id' => 'id']);
}
....
}

While writing filter query, add this relation like below.

Model ASeach file

namespace app\models;

use Yii;

class ASearch extends app\models\A
{
var $title = null;

public function search($params) {

$modelA = A::find();

$dataProvider = new yii\data\ActiveDataProvider([
  'query' => $query,
]);

$this->load($params);

$modelA->joinWith(['related']); //like this you can add more relations

$modelA->andFilterWhere(['like', 'b_title', $this->title]);

return $dataProvider;
}
}