yii2 activedataprovider 中的多对多关系
Many-to-many relation in yii2 activedataprovider
我与三个表存在多对多关系:Category
、Product
、ProductCategory
。
Category
中的关系:
public function getProductCategories()
{
return $this->hasMany(ProductCategory::className(), ['category_id' => 'id']);
}
Product
中的关系:
public function getProductCategories()
{
return $this->hasMany(ProductCategory::ClassName(), ['product_id' => 'id']);
}
并且在ProductCategory
public function getProduct()
{
return $this->hasOne(Product::className(), ['id' => 'product_id']);
}
public function getCategory()
{
return $this->hasOne(Category::className(), ['id' => 'category_id']);
}
在我的类别控制器中,我使用此代码根据类别(一对多)显示我需要的产品:
$cats = Category::findOne(['slug1'=>$slug1]);
$dataProvider = new ActiveDataProvider([
'query' => $query = Product::find()->where(['category_id' => $cats->id]),
'sort'=>array(
'defaultOrder'=>['id' => SORT_ASC],
),
'pagination' => [
'pageSize' => 9,
],
]);
所以问题是如何让我的 ActiveDataProvider 查询多对多关系?
你可以再创建两个这样的关系
类别:
public function getProducts()
{
return $this->hasMany(Product::className(), ['id' => 'product_id'])->via("productCategories");
}
在产品中:
public function getCategories()
{
return $this->hasMany(Category::ClassName(), ['id' => 'category_id'])->via("productCategories");
}
那你就可以这样使用了
$cats = Category::findOne(['slug1'=>$slug1]);
$dataProvider = new ActiveDataProvider([
'query' => $query = $cats->getProducts(),
'sort'=>array(
'defaultOrder'=>['id' => SORT_ASC],
),
'pagination' => [
'pageSize' => 9,
],
]);
我与三个表存在多对多关系:Category
、Product
、ProductCategory
。
Category
中的关系:
public function getProductCategories()
{
return $this->hasMany(ProductCategory::className(), ['category_id' => 'id']);
}
Product
中的关系:
public function getProductCategories()
{
return $this->hasMany(ProductCategory::ClassName(), ['product_id' => 'id']);
}
并且在ProductCategory
public function getProduct()
{
return $this->hasOne(Product::className(), ['id' => 'product_id']);
}
public function getCategory()
{
return $this->hasOne(Category::className(), ['id' => 'category_id']);
}
在我的类别控制器中,我使用此代码根据类别(一对多)显示我需要的产品:
$cats = Category::findOne(['slug1'=>$slug1]);
$dataProvider = new ActiveDataProvider([
'query' => $query = Product::find()->where(['category_id' => $cats->id]),
'sort'=>array(
'defaultOrder'=>['id' => SORT_ASC],
),
'pagination' => [
'pageSize' => 9,
],
]);
所以问题是如何让我的 ActiveDataProvider 查询多对多关系?
你可以再创建两个这样的关系
类别:
public function getProducts()
{
return $this->hasMany(Product::className(), ['id' => 'product_id'])->via("productCategories");
}
在产品中:
public function getCategories()
{
return $this->hasMany(Category::ClassName(), ['id' => 'category_id'])->via("productCategories");
}
那你就可以这样使用了
$cats = Category::findOne(['slug1'=>$slug1]);
$dataProvider = new ActiveDataProvider([
'query' => $query = $cats->getProducts(),
'sort'=>array(
'defaultOrder'=>['id' => SORT_ASC],
),
'pagination' => [
'pageSize' => 9,
],
]);