[英]Yii2 dataprovider with manytomany relation
我嘗試構建具有多對多關系的網格視圖。 所以我需要一個ActiveDataProvider
的查詢。
我有一個表'ressource',一個表'type',在它們之間有一個表'historique'。
我在模型中有很好的關系,但我不知道如何創建dataProvider。
在我的模型Ressource:
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']);
}
在我的模型Historique中:
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)中,我希望從表history中獲得類型的ressource。 我不知道我要添加什么
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
,你的查詢和力量的加盟關系表。 您可以使用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'],
];
}
您可以對該字段使用任何其他驗證規則
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.