Answer the question
In order to leave comments, you need to log in
How to make a many to many query in yii2?
Sorry if this question already exists. Started learning yii2. The documentation gives this many-to-many example:
class Order extends \yii\db\ActiveRecord
{
public function getItems()
{
return $this->hasMany(Item::className(), ['id' => 'item_id'])
->viaTable('order_item', ['order_id' => 'id']);
}
}
public function actionProducts()
{
return $this->hasMany(Product::className(), ['id' => 'product_id'])
->viaTable('product_category', ['id' => 'category_id']);
}
$category = Category::findOne(1);
$products = $category->actionProducts();
Answer the question
In order to leave comments, you need to log in
You can get a list of categories like this:
or, you can rename the actionProducts method to getActionProducts and then when $category->actionProducts is requested, the magic method will work, which will return what you need.
It's easier to look at the source code to understand how it works.
Here is another yiiframework.ru/doc/cookbook/ru/core.getters.setters
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question