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

Laravel中如何根据主键ID更新assets表的code字段?

How to Update code Field with Concatenated Primary Key in Laravel

No problem at all! Translating that MySQL update statement to Laravel's query builder is straightforward—you just need to use DB::raw() to tell Laravel to treat your concatenation logic as raw SQL instead of a plain string value.

Here's the exact code you need:

DB::table('assets')->update([
    'code' => DB::raw("CONCAT('ASSET000', id)")
]);

Why this works:

  • Without DB::raw(), Laravel would try to set code to the literal string CONCAT('ASSET000', id), which isn't what you want.
  • Wrapping the concatenation in DB::raw() tells the query builder to inject that snippet directly into the SQL, matching the behavior of your original MySQL statement perfectly.

Bonus: Consistent number formatting

If you want to ensure the ID portion of your code always has a fixed length (e.g., 4 digits, so ID 10 becomes ASSET0010 instead of ASSET00010), you can use MySQL's LPAD() function to pad the ID with leading zeros:

DB::table('assets')->update([
    'code' => DB::raw("CONCAT('ASSET', LPAD(id, 4, '0'))")
]);

This way, your code values will maintain a clean, uniform format no matter how large your primary key IDs grow.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:24:27