首页 > 解决方案 > 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块。它也没有工作。

标签: phplaravel-5

解决方案


推荐阅读