【问题标题】:how to retrieve data from 4 table with Eloquent relations in laravel如何在 laravel 中使用 Eloquent 关系从 4 个表中检索数据
【发布时间】:2021-08-28 12:51:48
【问题描述】:

我正在使用 laravel 8,并有下表及其模型结构

Orders
Id, store_id,client_id,delivery_date,created_at

order_details
Id,order_id,product_id,quantity,total_price

Products,
Id,product_name,product_image

users 
id,name,phone,address

我想根据订单ID从4个表中检索数据以显示订单的详细信息,例如以下json格式

{
   "id":1,
   "delivery_date":"20-06-2021",
   "created_at":"10-06-2021",
   "order_details":[
      {
         "id":1,
         "product_name":"TV",
         "product_image":"http://xxxx.com/images/tv.jpg",
         "quantity":1,
         "total_price":3000
      },
      {
         "id":1,
         "product_name":"playstation",
         "product_image":"http://xxxx.com/images/playstation.jpg",
         "quantity":3,
         "total_price":5000
      }
   ],
   "client":{
      "id":1,
      "name":"john",
      "address":"somewhere"
   }
}

但我不知道如何在 laravel 中使用关系和 eloquent 来获取这些数据编写代码

【问题讨论】:

  • 使用数据透视表 order_details laravel.com/docs/8.x/eloquent-relationships#many-to-many 和订单和客户之间的简单一对多关系,在订单和产品之间建立多对多关系。有关如何对其进行编码,请阅读文档,如果您在尝试时遇到问题,请发布问题。
  • 我会检查的

标签: laravel eloquent laravel-query-builder


【解决方案1】:

一些基本的想法可以帮助你。

订单模型

public function products(){
    
    $this->belongsToMany(Product::class,'order_details')->withPivot('quantity', 'total_price')->withTimestamps();;
}

public function client(){
    
    return $this->belongsTo(User::class,'client_id','id');
}

所以你可以像下面这样思考来访问它

Order::with(['products','client'])->find($orderId);

类似的问题,但在关系插入 参考:Attempt to read property "price" on null in laravel?

【讨论】:

  • order_details 不应该是模型,它是订单和产品之间的数据透视表。例如,您不能将代表同一产品的两个条目链接到同一订单。这就是数量字段的作用。
  • @N69S.thanks 指出我的错误。
猜你喜欢
  • 2019-12-11
  • 2022-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-28
  • 1970-01-01
  • 2021-06-04
相关资源
最近更新 更多