【问题标题】:Laravel Override Exception on NULL Object ReferenceNULL 对象引用上的 Laravel 覆盖异常
【发布时间】:2019-08-30 16:54:07
【问题描述】:

对于我的 API,我们接受大量 JSON 数据。有时当我们引用它时会丢失数据。因此,给定以下发布到 API 的 JSON:

{
    "reference_id": "6599",      
    "balance_0_30": "0",
    "balance_31_60": "0",
    "balance_over_90": "0",
    "account_balance": "0"
}

当我这样循环时:

foreach ($request->input('data') as $record) {
      $record = (object) $record;
      $accounting->reference_id = isset($record->reference_id) ? $record->reference_id : NULL;
      $accounting->reference_guarantor_id = $record->reference_guarantor_id ?: NULL;
      $accounting->balance_0_30 = isset($record->balance_0_30) ? $record->balance_0_30 : NULL;
      $accounting->balance_31_60 = isset($record->balance_31_60) ? $record->balance_31_60 : NULL;
      $accounting->balance_61_90 = isset($record->balance_61_90 ) ? $record->balance_61_90 : NULL;
      $accounting->balance_over_90 = isset($record->balance_over_90) ? $record->balance_over_90 : NULL;
      $accounting->account_balance = isset($record->account_balance) ? $record->account_balance : NULL;

这行得通,但阅读起来相当“混乱”,而且我有大约 4000 行类似的代码并且还在增长。

问题是,如果我在没有声明 account_balance 的情况下发送 JSON 数据,我会收到错误:

Undefined property: stdClass

我在想我可以写一个像这样的小函数:

function i($value) {
    if($value!=null){
        if(is_int($value)){
              return $value;
        }
        if(is_float($value)){
              return $value;
        }
    }
  return 0;
}

如果我知道该列是整数或浮点数,我可以这样称呼它:

$accounting->account_balance = i($record->account_balance);

如果该值为空,它只会填写一个 0 而不会出错。这将使事情更容易阅读、排除故障等。问题是异常在到达i函数之前就被抛出了。

我尝试使用此处所述的set_exception_handler(),包括来自 Glen 的类示例:https://www.php.net/manual/en/function.set-exception-handler.php,但它不起作用。

是我运气不好,还是有办法做我想做的事?

【问题讨论】:

    标签: php laravel exception


    【解决方案1】:

    你可以这样做:

    foreach ($request->input('data') as $record) {
        Accounting::create($record);
    }
    

    您的数据库列应该是 nullable 并且不要忘记在您的 Accounting 模型中设置 $fillable 属性(为此,您可以在模型中设置 protected $guarded = ['id', 'created_at', 'updated_at']; 以将所有其他列视为可填充)。

    【讨论】:

    • 这要简单得多,唯一的复杂之处是我们以 500 条为一组获取新记录,我们将其构建到 saveMany 中,然后在必须更新现有记录的地方进行增量更新。我确实看到这是一个好主意,但我希望我们仍然可以看看是否有办法处理异常以在其他地方使用
    猜你喜欢
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 2013-10-10
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多