Laravel更新Customer表points字段报错:1054列不存在问题
解决Laravel中Customer表更新points字段时的「Column not found」错误
问题场景
尝试更新Customer表的points字段值时,抛出以下SQL错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'points' in 'field list' (SQL: update
customerssetpoints= 400,customers.updated_at= 2023-01-11 06:05:40 whereid= 40)
问题根源
从提供的代码可以明确:
- Customer模型的
$appends数组包含points,这仅表示该字段是访问器追加的虚拟字段,并非数据库表中实际存在的列 - 查看
customers表的迁移文件,确实没有定义points字段 - 直接通过
Customer::where()->update(['points' => $total_sikka])执行SQL更新时,数据库找不到对应列,因此触发报错
解决步骤
1. 创建迁移添加points字段
首先需要为customers表添加实际的points字段,执行以下Artisan命令生成迁移文件:
php artisan make:migration add_points_to_customers_table
打开生成的迁移文件,修改up()和down()方法:
public function up() { Schema::table('customers', function (Blueprint $table) { // 根据业务需求选择字段类型,这里用unsignedInteger存储积分,默认值为0 $table->unsignedInteger('points')->default(0)->nullable(); }); } public function down() { Schema::table('customers', function (Blueprint $table) { $table->dropColumn('points'); }); }
执行迁移,将字段添加到数据库:
php artisan migrate
2. 更新Customer模型
将points添加到$fillable数组,允许通过批量赋值更新该字段:
protected $fillable = [ 'name', 'email','customer_number', 'password','customer_ph_number', 'points' ];
3. 优化更新代码
之前的代码中已经查询到$user模型实例,直接使用该实例更新,避免重复查询数据库:
public function newTransaction(Request $request){ $account = app()->make('account'); $user = Customer::withoutGlobalScopes() ->where('id', Auth::user('customer')->id) ->where('campaign_id', $campaign->id) ->firstOrFail(); $locale = request('locale', config('system.default_language')); app()->setLocale($locale); $previousSikka = $user->points; $sending_amount = $request->sending_amount; $remarks = $request->transaction_remarks; $latest_sikka = (int)($sending_amount / 100); $total_sikka = $latest_sikka + $previousSikka ; $NPRvalue = $total_sikka / 100; // 直接使用已查询的user实例更新 $user->update(['points' => $total_sikka]); return response()->json([ 'status'=>'success', "totalSikka" => $total_sikka, "total_sikka" => $total_sikka ],200); }
注意:原代码中
$customers_point变量未定义,已移除该字段避免运行报错
额外说明
如果points字段原本打算基于模型$hidden中存在的global_points计算生成,那么不需要添加数据库字段,而是定义对应的访问器和修改器即可:
// 访问器:获取points值 public function getPointsAttribute() { // 根据业务逻辑返回计算后的值,比如直接返回global_points return $this->attributes['global_points']; } // 修改器:更新points时同步到global_points public function setPointsAttribute($value) { $this->attributes['global_points'] = $value; }
这种情况下,读写$user->points时会自动映射到global_points字段,无需修改数据库结构。
内容的提问来源于stack exchange,提问作者ARBIND KUMAR
相关产品推荐
相关产品推荐

