1

玩弄 laravel 雄辩的关系。我有这些关系。

命令:

id
id_customer

订单.php

public function orderDetails(){
    return $this->hasMany('App\OrderDetail', 'order_id');
}

订单详情

id
order_id
product_id
quantity

订单详情模型

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

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

产品

id name price

当 dd'ed dd($this->order->with('orderDetails')->get();

我可以使用包含在订单详细信息中的产品 ID 来获取订单和订单详细信息。但我希望能够获得产品的名称,以便显示它。

我应该运行什么查询或更好的方式来定义我的关系?

4

2 回答 2

3

使用嵌套急切加载

$this->order->with('orderDetails', 'orderDetails.product')->get();

关系应该是belongsTo(),但不是hasMany()

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

此外,您可以在此处使用多对多关系。但只有在合适的情况下。

于 2017-01-04T17:14:01.793 回答
2

仅供所有访问此问题的人作为参考,正如您要求的关系建议,这是我可能实现这一目标的一种方式和我的观点。

它实际上产品属于许多订单,订单属于许多产品。我看到订单细节是一个支点。如果你愿意,你也可以为此创建一个模型。

products桌子

id
customer_id

产品.php

public function orders()
{
    return $this->belongsToMany(Order::class, 'order_details', 'order_id', 'product_id')->withPivot('quantity');
}

orders桌子

id
name
price

订单.php

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

我可能不会创建一个OrderDetail,因为没有对表格的可靠参考。只是order_details桌子

id
order_id
product_id
quantity

但是如果我要在这里创建 OrderDetail 模型,它会是怎样的

public function products()
{
    return $this->hasMany(Product::class, 'product_id');
}

public function orders()
{
    return $this->hasMany(Order::class, 'order_id');
}
于 2017-01-04T17:41:37.590 回答