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 setcodeto the literal stringCONCAT('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
相关产品推荐
相关产品推荐

