Answer the question
In order to leave comments, you need to log in
Yii2: How to display multiple one-to-many relationships in view?
Good day.
The task is to output in the form of a one-to-many relationship, but there can be several such relationships.
There are related tables of orders and products.
In the form you need to display all orders with products.
[ 1 order ] -> [ Product 1, Product 2, ... ]
[ 2 order ] -> [ Product 1, Product 2, ... ]
.....
My eye is already blurry, I can not find a solution to the problem. Thank you for your help / hint in which direction to dig.
-------- Update-------
In models:
public function getOrderItems() {
return $this->hasMany(OrderItems::className(), ['order_id' => 'id']);
}
public function getOrder() {
return $this->hasOne(Order::className(), ['id' => 'order_id']);
}
$orders = Order::find()->where(['email' => Yii::$app->user->identity['email']])->all();
foreach ($orders as $id => $items) {
$item = $items->getOrderItems()->all();
}
return $this->render('order', compact('orders'));
Answer the question
In order to leave comments, you need to log in
1. Set up links in the model
2. Load the product link and loop through and display all the data in it,
for example:
class Product extends \yii\db\ActiveRecord
{
...
}
class Order extends \yii\db\ActiveRecord
{
...
public function getProducts()
{
return $this->hasMany(Product::className(), ['order_id' => 'id']);
}
...
}
$orders = Order::find()->with('product')->all();
foreach ($orders as $order) {
foreach ($order->products as $product) {
echo 'Order id: ' . $order->id . ' Product Id: ' . $product->id;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question