laravel - 可以为空的外部的 belongsToMany - Laravel 5.8
问题描述
在我的 Laravel 项目中,我得到了这个数据库结构:
产品
- ID
- 姓名
订单
- ID
- 全部的
订购_产品
- Product_id (可为空)
- Order_Id
- 细节
在我的 Order 模型中,我对 Product 模型进行了 belongsToMany报复:
public function products() {
return $this->belongsToMany(Product::class)->withPivot('Details');
}
问题是当我尝试获取订单产品集合时
$order->products();
我没有得到可以为空 product_id的行,请问有什么解决方案吗?谢谢你。
解决方案
最有可能的是,您没有得到“可为空”的产品,因为您有一个关系 Order->Products。当您调用 $order->products() 时,eloquent 会尝试获取所有通过product_id字段连接到您的 Order 的Product 实体。因此,如果字段为空,则无法获取Product,因为没有连接。解决方案之一是:
- 创建另一个实体,例如OrderLine(Order_Product table);添加方法如 $orderLine->details() 和与Product的关系如 $orderLine->product()
- 在 Order中添加与OrderLine的关系- $order->line() 或 $order->info() 等 -> Order hasMany OrderLine
- 然后使用 $order->line() 获取订单的详细信息和产品(如果存在)
ps 我已经在脑海中编译了它,所以它可能需要一些代码调整。祝你好运
推荐阅读
- javascript - 从悬停框 Amcharts 更改颜色
- c - 为什么设置 AI_PASSIVE 时 getaddrinfo() 返回第一个 IPv4 而不是 IPv6?
- r - Creating multiple plots with facet_wrap in separated windows
- flutter - Flutter - Navigator.pushReplacementNamed show the same page
- javascript - 如何处理 React 表单字段中的空值?
- histogram - 选择不同 Bin 尺寸的 Tableau 构建参数。目标是拥有一个可以显示 3 个不同直方图的可视化
- facebook - URL Fetch App 无法获取所需的 URL
- reactjs - 我如何阻止我的链接被标记?
- python - IronPython 未按预期返回字典键
- php - Symfony 4 在创建实体时使用了错误的命名空间