mardi 7 août 2018

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: "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",
        }
    ]
 }

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.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire