【问题标题】:Laravel update() method yielding 'x doesn't have a default value' errorLaravel update() 方法产生“x 没有默认值”错误
【发布时间】:2020-09-07 14:34:48
【问题描述】:

我有一个包含以下值的表单:stage_name、stage_type、'client_id'、'created_at'、'updated_at'

我能够创建一种在表中添加新项目的方法,但是在尝试更新它时遇到了这个错误:

"SQLSTATE[HY000]: 一般错误: 1364 字段 'client_id' 没有默认值 (SQL: 插入stages (updated_at, created_at) 值 (2020-05-21 02: 43:53, 2020-05-21 02:43:53))"

我的控制器更新功能:

public function update(Request $request, Stage $stage)
{
    $request->validate([
        'stage_name'   => 'required|max:300',
        'stage_type'   => 'required'
    ]);

    $client = Auth::user()->client_id;

    $stage->update([
        'stage_name'          => $request-> stage_name,
        'stage_type'     => $request->stage_type,
        'client_id'   => $client, 
    ]);

    $stage->save();

    return $stage;
}

即使我直接定义 client_id => 1 它仍然会产生相同的错误

【问题讨论】:

  • 检查路由模型绑定是否有效。在函数的第一行执行dd($stage); 并检查是否正在获取正确的数据。并检查您的 Route 文件以查看类型提示的变量名称 $stage 是否与路由段名称 ../{stage} 匹配。

标签: php laravel controller updates


【解决方案1】:

您正在使用空的 save() 函数 $stage->save(); 并且您没有定义应该更新的记录。只需使用:-

$stage->where($column,$value) //othervise it will update all the records.
       ->update([
        'stage_name'          => $request-> stage_name,
        'stage_type'     => $request->stage_type,
        'client_id'   => $client, 
    ]);

此代码足以更新记录,无需添加save()。如果您想使用保存,请按照以下代码操作。

$stage = $stage->find($id);
$stage->stage_name = $request->stage_name;
$stage->stage_type = $request->stage_type;
$stage->client_id = $request->client;
$stage->save()

你混合了这两种方法。

【讨论】:

  • 在刀片模板中添加一个名为列的隐藏字段,并为出现错误的列添加受保护的可填充项。
  • OP 正在使用路由模型绑定,因此 $stage 应该已经加载了舞台模型。它不应该为空,update() 方法应该可以工作。但是是的,不需要$stage->save()。它已经在update() 失败了。使用 Laravel 的路由模型绑定,您无需显式定义查询来获取模型
猜你喜欢
  • 1970-01-01
  • 2019-02-05
  • 2017-12-09
  • 2020-07-04
  • 1970-01-01
  • 2017-07-31
  • 1970-01-01
  • 2021-01-05
相关资源
最近更新 更多