D
D
Denis Shpuganich2018-04-04 13:07:47
Yii
Denis Shpuganich, 2018-04-04 13:07:47

How to get data from Yii2 link table?

There are three tables:
Order - orders,
Product - products
Order2Product - linking table (fields: order_id, product_id, price, quantity)
The link between an order and products is defined by the following code:

public function getProducts()
    {
        return $this->hasMany(Product::class, ['id' => 'product_id'])
            ->viaTable('order2product', ['order_id' => 'id']);
    }

The question is, when receiving the order products, how to get additional data from the order2product table, for example, the quantity?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2018-04-04
@webinar

Make two connections, one through the other. And contact her.
https://www.yiiframework.com/doc/guide/2.0/ru/db-a...
There are two options, one like yours (with ->viaTable()) when the gap is not important and the second when it is needed (with - >via()).
Well, as an option, just add sql expression to select with COUNT. But I would use connections.

T
tigra, 2018-04-04
@tigroid3

get quantity count($model->orderProduct).
it should be understood that because hasMany connection, then orderProduct will contain an array of objects, or run by $model->orderProduct in a loop, or to a specific object by the key $model->orderProduct[0]->product->name
, you can also not through viaTable, but simply specify in with
in Order the relation

public function getProductOrder() {
      return $this->hasMany(Order2Product::class, ['id' => 'order_id'])
}

in Order2Product relationship
public function getProduct() {
     return $this->hasMany(Product::class, ['product_id' => 'id'])
}

and then in the query with(['orderProduct.product'])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question