1

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: "saging@gmail.com",
        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: "saging@gmail.com",
        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: "saging@gmail.com",
        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.

Beginner
  • 1,700
  • 4
  • 22
  • 42
  • I think you missed the id here `id: 11,` it's 12 no ? and please add the OrdersResource code :) – Maraboc Aug 07 '18 at 09:19
  • edited......... – Beginner Aug 07 '18 at 09:24
  • whats the problem ? you have added belongsTo relation between Order and Product then it will be always a single item – rkj Aug 07 '18 at 09:32
  • ohh i tried belongsToMany but im confused with it also because i have no idea what is pivot table i dont know where to start lol – Beginner Aug 07 '18 at 09:34
  • what i want is to display many item in order – Beginner Aug 07 '18 at 09:35
  • if you want to display multiple Products for single order then create a separate table `product_order` and place order_id, product_id and quantity in that table. After that create manyToMany relationship between Order and Product model using `product_order` as pivot table – rkj Aug 07 '18 at 09:37
  • can u show an example sir – Beginner Aug 07 '18 at 09:38

2 Answers2

2

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)
        ];
    
Maraboc
  • 10,550
  • 3
  • 37
  • 48
  • sir on my order table do i need to remove the column product_id and user_id? – Beginner Aug 07 '18 at 09:42
  • forgot about that remove only the product_id but the user_id it will be used for the user relationship leave it ;) – Maraboc Aug 07 '18 at 09:45
  • okay sir ill try. But how does the order_product table relate to that two model because i dont see any connection ? thanks sir – Beginner Aug 07 '18 at 09:49
  • all you have to do is add the columns prder_id and product_id and set the relationship and laravel will do the magic behind the scenes ;) – Maraboc Aug 07 '18 at 09:54
1

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

rkj
  • 8,067
  • 2
  • 27
  • 33
  • sir before im inserting the data only on orders table but now because of order_product table. Im inserting now the data in that 2 tables is that correct? – Beginner Aug 07 '18 at 10:18
  • in what table does that insert fall into? is that on order table and order_product? – Beginner Aug 07 '18 at 10:27
  • that will go to `pivot` table named `order_product`. read my answer from top – rkj Aug 07 '18 at 10:28
  • sir im using it like this $table = OrderProduct::with('product'); and im attaching it with $table->product()->attach($orders); and im getting an error query builder products not exist – Beginner Aug 07 '18 at 10:42
  • why `OrderProduct`, just create an order normally you do without `product_id` and `quantity` and then create `$order->products()->attach` – rkj Aug 07 '18 at 10:47
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/177561/discussion-between-rkj-and-beginner). – rkj Aug 07 '18 at 10:51
  • are u still there – Beginner Aug 08 '18 at 02:17
  • https://stackoverflow.com/questions/51738846/mysql-query-in-a-form-of-laravel-eloquent-orm – Beginner Aug 08 '18 at 05:00