1

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

我有一个表“资源”,一个表“类型”,它们之间有一个表“历史”。

我的模型关系很好,但我不知道如何创建 dataProvider。

在我的模型资源中:

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']);
}

因此,在控制器(实际上是我的 ModelSearch)中,我希望从表 historique 中获取具有类型的资源。我不知道我必须添加什么之后

Ressource::find();
4

1 回答 1

3

我认为你使用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的查询并强制加入关系表。您可以使用joinWith方法来加入附加关系并andFilterWhere使用table.field符号来添加过滤器参数。例如:

$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'],
        ];
    }

您可以对该字段使用任何其他验证规则

于 2016-04-26T08:33:34.947 回答