具有多对多关系的 Yii2 数据提供者

Yii2 dataprovider with manytomany relation

我尝试构建具有多对多关系的网格视图。所以我需要查询 ActiveDataProvider

我有一个 table 'ressource'、一个 table 'type' 和一个 table 'historique'.

我在我的模型中有很好的关系,但我不知道如何创建数据提供者。

在我的模型资源中:

public function getHistorique()
{
    return $this->hasMany(Historique::className(), ['idType' => 'idType']);
}



public function getType()
{
     return $this->hasMany(Type::className(), ['idType' => 'idType'])
        ->viaTable(Historique::className(), ['idRessource' => 'idRessource']);   
}

在我的历史模型中:

public function getType()
{
    return $this->hasOne(Type::className(), ['idType' => 'idType']);
}

public function getRessource()
{
    return $this->hasOne(Ressource::className(), ['idRessource' => 'idRessource']);
}

最后在我的模型中输入:

public function getHistorique()
{
    return $this->hasMany(Historique::className(), ['idType' => 'idType']);
}
public function getRessource()
{
    return $this->hasMany(Ressource::className(), ['idRessource' => 'idRessource'])
        ->viaTable(Historique::className(), ['idType' => 'idType']);
}

所以在 Controller(实际上是我的 ModelSearch)中,我想要具有来自 table historique 的类型的资源。我不知道我必须在

之后添加什么
Ressource::find();

我认为你使用 RessourceSearch()->search() 方法。所以在里面你有这样的东西:

$query = Ressource::find();

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

if (!($this->load($params) && $this->validate())) {
  return $dataProvider;
}

// Here is list of searchable fields of your model.
$query->andFilterWhere(['like', 'username', $this->username])
      ->andFilterWhere(['like', 'auth_key', $this->auth_key])


return $dataProvider;

所以,基本上,您需要添加额外的 Where 您的查询并强制加入关系 table。您可以使用 joinWith 方法加入附加关系并使用 table.field 符号添加过滤器参数 andFilterWhere 来做到这一点。例如:

$query = Ressource::find();
$query->joinWith(['historique', 'type']);
$query->andFilterWhere(['like', 'type.type', $this->type]);
$query->andFilterWhere(['like', 'historique.historique_field', $this->historique_field]);

另外不要忘记在您的搜索模型中添加额外过滤器的规则。例如上面的例子,你应该在你的 rules() 数组中添加这样的东西:

public function rules()
    {
        return [
            // here add attributes rules from Ressource model
            [['historique_field', 'type'], 'safe'],
        ];
    }

您可以为该字段使用任何额外的验证规则