首页 > 解决方案 > 可以为空的外部的 belongsToMany - Laravel 5.8

问题描述

在我的 Laravel 项目中,我得到了这个数据库结构:

产品

订单

订购_产品

在我的 Order 模型中,我对 Product 模型进行了 belongsToMany报复:

public function products() {
     return $this->belongsToMany(Product::class)->withPivot('Details');
}

问题是当我尝试获取订单产品集合时

$order->products();

我没有得到可以为空 product_id的行,请问有什么解决方案吗?谢谢你。

标签: laravellaravel-5eloquenthas-and-belongs-to-many

解决方案


最有可能的是,您没有得到“可为空”的产品,因为您有一个关系 Order->Products。当您调用 $order->products() 时,eloquent 会尝试获取所有通过product_id字段连接到您的 Order 的Product 实体。因此,如果字段为空,则无法获取Product,因为没有连接。解决方案之一是:

  1. 创建另一个实体,例如OrderLine(Order_Product table);添加方法如 $orderLine->details() 和与Product的关系如 $orderLine->product()
  2. 在 Order中添加与OrderLine的关系- $order->line() 或 $order->info() 等 -> Order hasMany OrderLine
  3. 然后使用 $order->line() 获取订单的详细信息和产品(如果存在)

ps 我已经在脑海中编译了它,所以它可能需要一些代码调整。祝你好运


推荐阅读