更新laravel控制器中存储列的内容



我有一个3列的表:firstname姓fullname

在迁移:

Schema::create('owners', function (Blueprint $table) {
$table->id(); 
$table->string('firstname',20);
$table->string('lastname', 20);
$table->string('fullname')->storedAs('CONCAT(firstname,lastname)');
$table->timestamps(); 
});

问题是我想改变控制器中的连接顺序我试图使用db语句,但它不起作用

-in the controller:

$owners= Owner::findOrFail($id);
$owners->update([
'firstname'=>$request['firstname'],
'lastname' =>$request['lastname'],
]); 
DB::statement('UPDATE owners SET fullname AS CONCAT(lastname,firstname) STORED WHERE ID=1 ');

我不想只使用简单的连接因为用户可以更改姓或名和顺序这就是为什么我使用storedAs()

有什么想法吗?

迁移中的storedAs方法在mysql中创建了一个生成的列。该值是根据姓和名的列值自动生成的。你不可能通过UPDATE语句来改变这个。您必须使用ALTER TABLE语句,这将是非常糟糕的做法。

如果我是你,我会把全名显示作为一个模型方法,这样你就可以通过使用$owner->fullNameFirstLast()$owner->fullNameLastFirst()来访问它

您应该做的是创建一个新的迁移,以便更改列,代码将是这样的:

Schema::table('owners', function (Blueprint $table) {
$table->string('fullname')->storedAs('CONCAT(lastname,firstname)');
});

这样可以在数据库级别更改列,并且不需要添加

的控制器查询。

试试这个1-更新你的迁移到

Schema::create('owners', function (Blueprint $table) {
$table->id(); 
$table->string('firstname',20);
$table->string('lastname', 20);
$table->string('fullname', 56);
$table->timestamps(); 
});

2-在你的控制器

$owners= Owner::findOrFail($id);
$first_name = $request->firstname ?? $owners->firstname;
$last_name = $request->lastname ?? $owners->lastname;
$full_name = $first_name.' '.$last_name;
$owners->update([
'firstname'=>$first_name,
'lastname' =>$last_name,
'fullname' =>$full_name,
]); 

你也可以这样写

DB::statement(DB::raw("UPDATE owners SET firstname = '".$first_name."', lastname = '".$last_name."', fullname = '".$full_name."' WHERE id = $id"));

同样的方法创建功能良好

最新更新