0
votes

I'm building an application for product orders..

a client can access to the app , pass an order for specific products

let's say :

Product A / Quantity : 10

Product B / Quantity : 20

this order will pass to administration so an admin will prepare those ordered products depending on what existing in warehouses ( where products are physically stored)

One product can have many instances..

for example :

Product A can be stored in 3 warehouses but with different holded data such as creation,expiration_date that differentiate from an instance to another

so admin has to pick up a product from warehouses and prepare it for the upcoming order

I have these tables below :

  • Product
  • Warehouse
  • ProductWarehouse ( pivot between Product And Warehouse)
  • Order
  • OrderProductWarehouse ( pivot between ProductWarehouse And Order to define the prepared products of an upcoming order)

the issue now is I want to list the prepared products grouped by product_id

when I'm doing :

$order=Order::find(1);
$order->productwarehouses  //relationship defined in order model to get the related products in warehouses

I can see all the prepared products but not grouped by "product_id"...

what I want to achieve is this below :

[
{
product_id : 1

prepared_products: [
{ product_id: 1,
  expiration_date:12/10/2019},
{ product_id: 1,
  expiration_date:08/10/2019}
}

]},


{
product_id : 2

prepared_products: [
{ product_id: 2,
  expiration_date:10/10/2019},
{ product_id: 2,
  expiration_date:04/10/2019}
}

]}


}]

I hope it's clear and you can help me!

1

1 Answers

0
votes

I reckon you have a pivot table to store order products

You have to:

Create a belongsToMany relationship in Order model for products.

//Order.php
public function products()
{
     return $this->belongsToMany('App\Product','order_product');//order_product is your pivot table to store order products
}

Create a hasMany relationship in Product model for productwarehouses.

//Product.php
public function productwarehouses()
{
     return $this->hasMany('App\Warehouse','ProductWarehouse'); //ProductWarehouse is your table name
}

Now you can fetch Order Products with details as:

$order->products()->with('productwarehouses')->get();