2016-04-26 109 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

我会试试这个谢谢你的回答,它真的帮了我:) –