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

Laravel中如何为website_setup表已存在的key插入对应value

解决方案

原代码问题梳理

  • insertGetId 为新增数据行方法,无法实现对已有行的value更新,执行后会生成key字段为空的无效数据
  • 链式调用的select('header_logo')在写入类操作中无任何作用,你需要用where条件筛选key字段值为header_logo的目标行
  • 你当前的写入逻辑未给必填的key字段赋值,会触发数据库字段非空报错

正确实现

场景1:已确定对应key预存在表中,直接执行更新

public function store($request)
{
    // 先做参数验证,避免非法数据写入
    $validated = $request->validate([
        'header_logo' => 'required|string'
    ]);

    return DB::table('website_setup')
        ->where('key', 'header_logo')
        ->update([
            'value' => $validated['header_logo'],
            'updated_at' => now() // DB门面不会自动维护时间戳,需手动赋值
        ]);
}

场景2:兼容key不存在的情况,不存在则自动创建

如果需要支持当key不存在时自动新增对应行,可以使用updateOrInsert方法:

public function store($request)
{
    $validated = $request->validate([
        'header_logo' => 'required|string'
    ]);

    return DB::table('website_setup')
        ->updateOrInsert(
            ['key' => 'header_logo'], // 匹配条件
            [
                'value' => $validated['header_logo'],
                'updated_at' => now()
            ]
        );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:45:01