W
W
WebDev2015-01-16 22:06:23
MySQL
WebDev, 2015-01-16 22:06:23

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']);
    }
}

Please explain where and what to insert, I'm talking about the second parameters (arrays) in methods.
Let's say I have a category(id, name) table, a product(id, name) table, and a product_to_category(id, product_id, category_id) table. How can I select all products from a specific category?
I try like this: Created 2 models Product and Category.
Created a method in Category:
public function actionProducts()
  {
        return $this->hasMany(Product::className(), ['id' => 'product_id'])
            ->viaTable('product_category', ['id' => 'category_id']);
  }

Now in the controller I write:
$category = Category::findOne(1);

$products = $category->actionProducts();

An object with a list of categories is returned. Please explain what and where to substitute id to get goods from one category?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Filatov, 2015-01-16
@kirill-93

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 question

Ask a Question

731 491 924 answers to any question