Answer the question
In order to leave comments, you need to log in
How to correctly select many_many in Yii2?
There are tables
products [id, name, publish, ....]
category [id, name, parent_id...]
products_to_category
[product_id, category_id]
AUDI, OPEL, (the main category for all auto parts) then there will be 3 products in the Auto parts category, the
selection is done like this:
An excerpt from ProductsSearch.php search method
$query = Products::find();
....
$query->joinWith('categories');
$query->andFilterWhere(['category.parent_id' => $this->mainCategoryID]);
public function getCategories() {
return $this->hasMany(Category::className(), ['id' => 'category_id'])
->viaTable('products_to_category', ['product_id' => 'id']);
}
public function getParent()
{
return $this->hasOne(Category::className(), ['id' => 'parent_id']);
}
SELECT COUNT(*) FROM `products` LEFT JOIN `products_to_category` ON `products`.`id` = `products_to_category`.`product_id` LEFT JOIN `category` ON `products_to_category`.`category_id` = `category`.`id` WHERE (`category`.`parent_id`=1) AND (`publish`=1)
Answer the question
In order to leave comments, you need to log in
This is a problem of logic. It is necessary to rewrite the method that counts. You are not alone, the regular method does not work correctly with such samples.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question