php - PHP - 访问深层对象的深层属性时处理错误的最佳方法是什么?
问题描述
我正在开发一个具有复杂模型关系的项目(Laravel)
我有 10 多个带有许多外键的表。
现在,当通过多个级别的 eloquent 对象访问深层属性时,我不得不处理错误。
以下是关系示例
Category
||
||
Product === Seller === User === Country === Region
|| || ||
|| || ||
Cart Seller Level Buyer
|| ||
|| ||
Invoice ==============================
这是一个从指定发票获取卖家/买家所在国家/地区的简单脚本 - Eloquent
$invoice = Invoice::find($id);
$countrySeller = $invoice->cart->product->seller->user->country; //6 levels
$countryBuyer = $invoice->buyer->user->country; // 4 levels
在运气不好的一天,脚本出现错误Trying to get property of non-object
-laravel.log
没有错误行。
调试后,我发现了问题。缺少访问财产的数据。
第一个解决方案看起来很疯狂。它正在检查是否为所有子属性设置
if (isset($invoice->buyer) && isset($invoice->buyer->user) && isset($invoice->buyer->user->country)) {
// Do sth
}
我试图将上面的脚本包装成try-catch
块。它也没有工作。
解决方案
推荐阅读
- c++ - Lisp 像 C++ 函数调用 std::tuple 和折叠表达式
- excel - 按列计算其他 3 列之一中的一个条件
- node.js - NestJS:复制资产不适用于 Linux
- azure - 如何获取 RunCommandResult 以确定是否有错误?
- wpf - 如何使用具有多个路径的 Svg 图像
- reactjs - 在执行 axios 发布请求时,如何解决与打字稿反应时未捕获的承诺错误?
- abap - ABAP:如何获取事务的参数名称以在 SET PARAMETER ID 中使用?
- asp.net-core - 复杂类型数组的OpenApi 3多部分表单请求
- css - 如何在 Material UI 中插入变量类名?
- amazon-web-services - AWS Glue 架构注册表导入