2016-04-26 133 views
1

我嘗試建立一個多對多關係的網格視圖。所以我需要查詢ActiveDataProviderYii2 dataprovider與manytomany關係

我有一個表「資源」,一個表「類型」,他們之間的表'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']); 
} 

在我的模型歷史之:

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),我想要使用來自表歷史的類型的資源。我不知道我要添加什麼

Ressource::find(); 

回答

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

你可以使用任何額外的驗證規則,表格中

+0

感謝我不敢靠近。我只有最後一個問題:在gridView中,當我使用GridView :: widget(['dataProvider'=> $ dataProvider])時,它可以工作。但是,當我想從其他表格中選擇一些列的網格視圖屬性而不是來源不明時。我應該從GridView的屬性寫什麼? –

+1

@SamaëlVillette你也應該使用點符號的屬性或列名'relation.attribute' –

+0

我會試試這個謝謝你的回答,它真的幫了我:) –