mercredi 13 mai 2020

How to use multiple relations in Laravel

Can some one tell me how to use multiple relations in Laravel Im try explain the situation Im have 3 tables in database as like users, orders and order products Each of these tables is linked by a foreign key. Im have response like this

address: "test"
birthday: "01-01-2020"
created_at: null
email: "admin@admin.com"
email_verified_at: null
id: 1
name: "Admin"
orders: [,…]
0: {id: 73, user_id: 1, orderNumber: "2180673", total: "350", status: "1", delivery: "1", comment: null,…}
comment: null
created_at: "2020-05-13T20:27:28.000000Z"
delivery: "1"
id: 73
orderNumber: "2180673"
status: "1"
total: "350"
updated_at: "2020-05-13T20:27:28.000000Z"
user_id: 1
phone: "+380991111111"
role: "admin"
surname: "Admin"
uniqueId: null
updated_at: null

Is it possible to get response like this

address: "test"
birthday: "01-01-2020"
created_at: null
email: "admin@admin.com"
email_verified_at: null
id: 1
name: "Admin"
orders: [,…]
0: {id: 73, user_id: 1, orderNumber: "2180673", total: "350", status: "1", delivery: "1", comment: null,…}
comment: null
created_at: "2020-05-13T20:27:28.000000Z"
delivery: "1"
id: 73
orderNumber: "2180673"
order_products: [{id: 3, order_id: 73, product_id: 1, quantity: "1", name: "Test", price: "250",…},…]
0: {id: 3, order_id: 73, product_id: 1, quantity: "1", name: "Test", price: "250",…}
1: {id: 4, order_id: 73, product_id: 2, quantity: "1", name: "Test2", price: "100",…}
status: "1"
total: "350"
updated_at: "2020-05-13T20:27:28.000000Z"
user_id: 1
phone: "+380991111111"
role: "admin"
surname: "Admin"
uniqueId: null
updated_at: null

This is my code in User model file

 public function orders()
{
    return $this->hasMany('App\Order', 'user_id', 'id');
}

This is my code in Order model file

public function user()
{
    return $this->belongsTo('App\User', 'user_id', 'id');
}

public function orderProducts()
{
    return $this->hasMany('App\OrderProduct', 'order_id', 'id');
}

This is my code in OrderProduct model file

public function order()
{
    return $this->belongsTo('App\Order', 'order_id', 'id');
}

public function product()
{
    return $this->belongsTo('App\Product', 'product_id', 'id');
}

If someone have info about this it will be so great



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire