【问题标题】:Laravel hasManyThrough in depthLaravel hasManyThrough 深入
【发布时间】:2017-12-08 17:44:37
【问题描述】:

我一直在查看有关 Laravel 中 hasManyThrough 关系的文档,出于某种原因,我正在努力解决它,因为文档使它看起来很简单(也许我想多了)......

我目前有三个模型表:

-User (extends authenticatable)
    id, 
    name, 
    surname, 
    email, 
    password.

-Order
    id, 
    user_id, 
    name, 
    unit, 
    qty

-Product (i need to add a qty table to show how many is ordered).
    id, 
    order_id, 
    name, 
    unit, 
    description, 
    family

管理员将我的产品模型用于 CRUD 产品。

请有人向我解释一下我将如何向管理员显示哪个用户下了订单,以及订单的组成部分。 我还想向用户显示“订单历史记录”..

请任何人都可以提供帮助..

更新

-order_product
  id,
  order_id,
  product_id
  quantity

产品负责人:

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

订单控制器:

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

【问题讨论】:

  • 提及表格字段
  • 用户字段:id、name、surname、email、password。订单字段:id、user_id、name、unit、qty 产品字段:id、order_id、name、unit、description、family
  • 它的多对多关系。没有多少经过。并且您的数量表应命名为 order_product,其中应包含 id、product_id、order_id、qty laravel.com/docs/5.4/eloquent-relationships#many-to-many 等字段
  • 所以我将有一个名为“order_product”的数据透视表,我最初是这么想的,但在我开始之后,我想知道如果它没有 user_id 列,它将如何跟踪哪个用户下订单?跨度>
  • 用户 ID 列在您的产品表中。您可以按 user_id 对所有订单进行分组。

标签: laravel has-many-through relationships


【解决方案1】:

关系显示是多对多的,您必须创建另一个名为的数据透视表 order_product 带字段

-id

-order_id

-product_id

-数量

并在您的订单表模型中将关系定义为

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

并在您的产品表模型中将关系定义为

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

检索数据

$order= App\Order::find(1);

@foreach ($order->products as $product)
    echo $product->pivot->quantity."<br>";
@endforeach

【讨论】:

  • 我现在很困惑。我需要通过 user_id 搜索订单,user_id 必须包含该用户曾经下过的所有订单,如果我点击其中一个订单,必须出现订购的产品列表?
  • 发布有问题的代码,以便清楚了解您到目前为止所做的工作
  • 对不起,我是堆栈溢出的新手,我似乎无法以正确的格式获取我的代码
  • 点击问题下方的编辑并在末尾提及新代码
  • 如何获取数据?提及输出
【解决方案2】:

我认为您需要再创建一个类似 order_details 的表

-User (extends authenticatable)
    id, 
    name, 
    surname, 
    email, 
    password.

-Order
    id, 
    user_id, 
    name, 
    unit, 
    qty

-Product (i need to add a qty table to show how many is ordered).
    id, 
    name, 
    unit, 
    description, 
    family
-Order_detail(Store product_id, order_id (You can put qty to this table))
    id,
    order_id,
    product_id

【讨论】:

    猜你喜欢
    • 2021-12-06
    • 2014-09-19
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 2014-08-14
    • 2018-10-18
    • 2021-08-30
    相关资源
    最近更新 更多