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

Laravel 5.3无法更新特定行:webcart表按identifier更新字段问题

解决webcart表按交易ID更新数据的问题

嘿,我一眼就看出你代码里的问题啦——你用findOrFail($txnid)去查找记录,但这个方法默认是按模型的**主键字段(一般是id)**来查询的,而你的交易ID存在identifier字段里,所以肯定找不到对应的数据,更新自然就失败了。

下面给你几种正确的实现方案,还有关于findOrFail的详细说明:

方案一:通过where条件定位记录后更新

这是最直观的方式,明确指定用identifier字段匹配交易ID:

$amount = $request->amount; 
$status = $request->status; 
$reason = $request->unmappedstatus; 
$txnid = $request->txnid; 

// 用where匹配identifier字段,找不到就抛出异常(和findOrFail逻辑一致)
$device = webcart::where('identifier', $txnid)->firstOrFail(); 
$device->update([ 
    'amount' => $amount,
    'status' => $status,
    'reason' => $reason 
]);

方案二:直接通过where+update批量更新(更高效)

如果不需要操作模型实例,只是单纯更新数据,这种方式省去了查询实例的步骤,性能更好:

webcart::where('identifier', $request->txnid)
    ->update([
        'amount' => $request->amount,
        'status' => $request->status,
        'reason' => $request->unmappedstatus
    ]);

关于findOrFail方法的参数说明

findOrFail()方法默认只认模型的主键字段,默认情况下Laravel模型的主键是id字段,所以你传入交易ID(存在identifier里)肯定查不到。

如果你想让findOrFail直接用identifier查询,可以修改你的webcart模型,把identifier设为主键:

class webcart extends Model
{
    // 指定主键为identifier字段
    protected $primaryKey = 'identifier';
    // 如果identifier不是自增的整数类型,必须加上这句
    public $incrementing = false;
}

修改之后,你原来的webcart::findOrFail($txnid)就能正常工作了,因为模型现在把identifier当作主键处理。

额外提醒

  • 记得确保$txnid确实存在于identifier字段中,不然firstOrFail或修改后的findOrFail会抛出异常,你可以根据业务需求用try-catch捕获异常做友好提示。
  • Laravel的模型类名建议用大驼峰命名(比如Webcart),这是框架的编码规范,能避免一些潜在的问题。

内容的提问来源于stack exchange,提问作者Shubham Dixit

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:55:25