具有可为空的外国人的belongsToMany-Laravel 5.8

时间:2019-07-05 09:01:10

标签: laravel laravel-5 eloquent has-and-belongs-to-many

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

产品

  • 编号
  • 名称

订单

  • 编号
  • 总计

订单产品

  • Product_id (可空)
  • Order_Id
  • 详细信息

在我的订单模型中,我对产品模型进行了 belongsToMany 报复:

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

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

$order->products();

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

2 个答案:

答案 0 :(得分:0)

Laravel从5.5版开始支持“空对象模式”,它允许您定义默认模型,如果给定关系为null,则将返回该默认模型。

尝试使用以下代码:

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

答案 1 :(得分:0)

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

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

p.s。我已经将其编译在脑海中,因此可能需要一些代码调整。 祝你好运