1

I have many-to-many relation with three tables: Category, Product, ProductCategory. Relation in Category:

public function getProductCategories()
{
    return $this->hasMany(ProductCategory::className(), ['category_id' => 'id']);
}

Relation in Product:

    public function getProductCategories()
{
    return $this->hasMany(ProductCategory::ClassName(), ['product_id' => 'id']);
}

And in ProductCategory

public function getProduct()
{
    return $this->hasOne(Product::className(), ['id' => 'product_id']);
}

public function getCategory()
{
    return $this->hasOne(Category::className(), ['id' => 'category_id']);
}

In my Category Controller I used this code to show the products I need according to their category (one-to-many):

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

So the question is how to make my ActiveDataProvider to get in query the many-to-many relation?

andrew
  • 15
  • 3

1 Answers1

1

You can create two more relations like this

In category:

public function getProducts()
{
   return $this->hasMany(Product::className(), ['id' =>   'product_id'])->via("productCategories");
}

And in product:

public function getCategories()
{
  return $this->hasMany(Category::ClassName(), ['id' =>   'category_id'])->via("productCategories");
}

Then you can use it like this

$cats = Category::findOne(['slug1'=>$slug1]);
$dataProvider = new ActiveDataProvider([

    'query' => $query = $cats->getProducts(),
    'sort'=>array(
        'defaultOrder'=>['id' => SORT_ASC],
    ),
    'pagination' => [
        'pageSize' => 9,
    ],
]);
Golub
  • 170
  • 1
  • 8
  • Thanks! But the question was how to pass this relation to the $query to show relative Products in my view. I would really appreciate your help. – andrew Mar 16 '18 at 13:58
  • Sorry, just write ` 'query' => $cats->getProducts()` – Golub Mar 16 '18 at 14:01
  • Just add $query = Product::find()->where(['category_id' => $cats->id])->joinWith(['Category']); – Sfili_81 Mar 16 '18 at 14:04
  • so strange, now I have an error: Invalid Parameter – yii\base\InvalidParamException app\models\Category has no relation named "productsCategories". (it's the answer to Golub) – andrew Mar 16 '18 at 14:05
  • as to Sfili_81 comment, it first told me it's case sensitive< so I just replaced 'Category' with 'category'. Now it renders my page but shows no products in this categories :( – andrew Mar 16 '18 at 14:10
  • phew! I have found the error. In Golub's code there's via("productsCategories") while it should be via("productCategories") thank you very much! – andrew Mar 16 '18 at 14:18
  • @andrew sorry for typo, I'm glad I was able to help. – Golub Mar 16 '18 at 14:53