You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel项目报错:尝试获取非对象的'sales_price'属性求助

问题分析与解决

错误根源

Trying to get property 'sales_price' of non-object 异常的本质是:当PosCustomerProducts查询语句找不到匹配的记录时,->first()会返回null(非对象),此时直接链式调用->sales_price就会触发该错误。

修复方案

1. 修正helper.php中的方法

修改getSalesPriceUsingProductIDCode方法,先判断查询结果是否存在,再获取sales_price:

public static function getSalesPriceUsingProductIDCode($id, $customerId)
{
    // 先获取查询结果,避免直接链式访问属性
    $customerProduct = PosCustomerProducts::valid()
        ->where('complete_status', 0)
        ->where('customer_id', $customerId)
        ->where('product_id', $id)
        ->select('product_id', 'sales_price')
        ->first();

    // 存在记录则返回sales_price,无匹配时返回0(可根据业务需求调整默认值)
    return $customerProduct ? $customerProduct->sales_price : 0;
}

2. 优化orderSheetExport.php中的代码

原代码重复调用3次查询方法,既浪费性能也增加风险,建议先将结果存入变量复用:

if(isset($results[$product->id]))
{   
    // 仅查询一次销售价格,避免重复访问数据库
    $salesPrice = Helper::getSalesPriceUsingProductIDCode($product->id, $results['customer_id']);
    
    $total = $salesPrice == 0 
        ? $product->whole_sale_price * $results[$product->id] 
        : $salesPrice * $results[$product->id];

    $excel_dynamic_data_values[$index][] = $total;
    $productArray[$rsm_id][$product->id] += $total;
    $singleProductArray[$rsm_id][$product->id] = $productArray[$rsm_id][$product->id];
}

额外提示

  • 可在数据库层面给sales_price字段设置默认值,确保即使有记录也不会出现非数值情况。
  • 如果业务需要严格校验记录存在性,也可以使用firstOrFail()配合异常捕获,但当前场景返回默认值0更适配业务逻辑。

内容的提问来源于stack exchange,提问作者Anika Tabassum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 15:20:31