Beginner
Beginner

Reputation: 1740

laravel eloquent relationship multiple

This is my products model

public function orders(){
    return $this->hasMany(Order::class);
}

and this is my Orders model

 public function user(){
      return $this->belongsTo(User::class);
 }
 public function product(){
      return $this->belongsTo(Product::class);
 }

and my order table structure

enter image description here

this is my response as of now (I'm using Order model).

{
    id: 11,
    quantity: 2,
    customer: {
        id: 6,
        name: "saging",
        email: "[email protected]",
        role_id: 3,
    },
    items: {
        id: 7,
        name: "Pellentesque semper",
        description: "raesent sit amet elementum purus. ",
        price: "72.21",
        cover_image: "7CPVS7yjqba9iJ7J.jpg",
    }
},

{
    id: 12,
    quantity: 2,
    customer: {
        id: 6,
        name: "saging",
        email: "[email protected]",
        role_id: 3,
    },
    items: {
        id: 3,
        name: "Donec nec mattis ligula",
        description: "Pellentesque semper, augue at aliquet tincidunt",
        price: "33.21",
        cover_image: "ZJbbzjPwDXrcbkwi.jpg",
    }
 }

the code that im currently using is

$products = Order::with('user','product');
return OrdersResource::collection($products->paginate(5));

and im listing the products and customer by using the methods in my Order Model

the output that i want is like this

{
    id: 12,
    quantity: 2,
    customer: {
        id: 6,
        name: "saging",
        email: "[email protected]",
        role_id: 3,
    },
    items: [
        {
            id: 3,
            name: "Donec nec mattis ligula",
            description: "Pellentesque semper, augue at aliquet tincidunt",
            price: "33.21",
            cover_image: "ZJbbzjPwDXrcbkwi.jpg",
        },
        {
            id: 7,
            name: "Pellentesque semper",
            description: "raesent sit amet elementum purus. ",
            price: "72.21",
            cover_image: "7CPVS7yjqba9iJ7J.jpg",
        }
    ]
 }

this is my OrderResource Code

$sub_total = $this->quantity * $this->product->price;
$discount = round((10 / 100) * $sub_total, 2);
$total = $sub_total - $discount;

return [
    'id' => $this->id,
    'quantity' => $this->quantity,
    'address' => $this->address,
    'sub_total' => $sub_total,
    'discount' => $discount,
    'total_price' => $total,
    'created_at' => Carbon::parse($this->created_at)->format('F d, Y h:i:s A'),
    'customer' => $this->user,
    'items' => $this->product,
    ];

Is my relationship wrong? I'm new to laravel and the eloquent relationship is the part where i always skipped because I'm confuse. But now i have to face it.

Upvotes: 1

Views: 83

Answers (2)

rkj
rkj

Reputation: 8287

Remove product_id and quantity from orders table and create a table order_product like this

order_product(id, order_id, product_id, quantity)

Order model

public function products()
{
    return $this->belongsToMany('App\Product')->withPivot('quantity')->withTimestamps();
}

Product model

public function orders()
{
    return $this->belongsToMany('App\Order')->withPivot('quantity')->withTimestamps();
}

Now create a ProductResource class

return [
    'id' => $this->id,
    'name' => $this->name,
    'description' => $this->description,
    'price' => $this->price,
 ];

Now change in OrderResource class

$sub_total= 0;
$quantity = 0;

foreach($this->products as $product){
  $sub_total += ($product->pivot->quantity * $product->price);
  $quantity += $product->pivot->quantity;
}

$discount = round((10 / 100) * $sub_total, 2);

$total = $sub_total - $discount;

return [
    'id' => $this->id,
    'quantity' => $quantity,
    'address' => $this->address,
    'sub_total' => $sub_total,
    'discount' => $discount,
    'total_price' => $total,
    'created_at' => Carbon::parse($this->created_at)->format('F d, Y h:i:s A'),
    'customer' => $this->user,
    'items' => ProductResource::collection($this->products),
    ];

After creating order, insert order product like this

$order->products()->attach([
    10 => ['quantity' => 1],
    22 => ['quantity' => 2]
]);

Here 10 and 22 is a product id

Check details here https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

Upvotes: 1

Maraboc
Maraboc

Reputation: 11083

There is a problem in the relationships between order and products, you have to set a Many to Many relationship, for that you will need :

  • Create a third table name it order_product is should contain order_id and product_id

  • set the relationsips in the models :

    Product model :

    public function orders()
    {
        return $this->belongsToMany('App\Order');
    }
    

    Order model :

    public function products()
    {
        return $this->belongsToMany('App\Product');
    }
    
  • Finally you have to create a ProductResource and in the OrderResource you have to do it like this :

    return [
        'id' => $this->id,
        'quantity' => $this->quantity,
        'address' => $this->address,
        'sub_total' => $sub_total,
        'discount' => $discount,
        'total_price' => $total,
        'created_at' => Carbon::parse($this->created_at)->format('F d, Y h:i:s A'),
        'customer' => $this->user,
        'items' => ProductResource::collection($this->products)
        ];
    

Upvotes: 2

Related Questions