Answer the question
In order to leave comments, you need to log in
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']);
}
Answer the question
In order to leave comments, you need to log in
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.
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'])
}
public function getProduct() {
return $this->hasMany(Product::class, ['product_id' => 'id'])
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question