D
D
Daniil Sidorov2016-10-04 13:58:41
Yii
Daniil Sidorov, 2016-10-04 13:58:41

How to link independent tables in yii2?

There are 3 models:

  • Product (id, category_id, manufacturer_id)
  • Category (id, name)
  • Manufacturer (id, name)

I want the Categories page to display a table with the products in that category.
Get a list of products I was able to (Category.php)
public function getProducts()
    {
        return $this->hasMany(Product::className(), ['category_id' => 'id']);
    }

But how can I get the manufacturer now if I only store the manufacturer's id in the Product model?
And how can I get it out?
Thank you!
PS I found something about Via and ViaTable, but I couldn't connect them.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2016-10-04
@DaniLaFokc

public function getManufactures()
{
    return $this->hasMany(Manufacturer::className(), ['id' => 'manufacturer_id'])
        ->viaTable('products');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question