我的MySQL数据库排序规则是:utf8mb4_unicode_ci如下所示:
但是,当我尝试使用Laravel将其插入表中时,它会引发以下错误:
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect string value: '\xF0\x9F\x98\x89' for column `challenges`.`challenges`.`description` at row 1 (SQL: insert into `challenges` (`hashtag`, `title`, `description`, `challenge_id`, `image_name`, `category_id`, `duration`, `link`, `user_id`, `updated_at`, `created_at`) values (emojiasd, Emoji Test, Hey this is an emoji 😉, 5edccab9327c4, challenge-55edccab9327e81591528121.png, 2, 0, ?, 5ec443a71e40b, 2020-06-07 11:08:41, 2020-06-07 11:08:41))
这是我控制器中的存储方法:
public function store(Request $request)
{
//
$this->validate($request, [
'hashtag' => 'required',
'title' => 'required',
'description' => 'required',
'category' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
'duration' => 'required'
]);
$challenge = new Challenge;
$replace = array (' ', '#');
$challenge->hashtag = strtolower(str_replace($replace, '', $request->input('hashtag')));
$challenge->title = $request->input('title');
$challenge->description = $request->input('description');
$challenge->challenge_id = uniqid();
$image = $request->file('image');
$imageName = 'challenge-' . uniqid(5) . time() . '.' . $image->extension();
$image->move(storage_path('app/public/challenges/'), $imageName);
$challenge->image_name = $imageName;
$challenge->category_id = $request->input('category');
if ($request->input('duration') == 1) {
$challenge->duration = $request->input('duration_days');
} else {
$challenge->duration = 0;
}
$challenge->link = $request->input('link');
$challenge->user_id = Auth::id();
$challenge->save();
return redirect('/')->with('success', 'Challenge Created');
}
这更多的是数据库和迁移的最终问题,然后在laravel上出现错误的格式错误。请尝试:
1)数据库:将数据库默认排序规则更改为utf8mb4。看起来都完成了
2)表:将表排序规则更改为CHARACTER SET utf8mb4 COLLATE utf8mb4_bin。
查询:
更改表表名转换为字符集utf8mb4收集utf8mb4_bin
3)代码:
运行插入查询以获得能够处理表情符号的初始测试插入表名(列名)中的值“”
4)在数据库连接中设置utf8mb4:
使用原始mysql查询编写更新表迁移脚本并运行php artisan migration命令
使用Illuminate \ Database \ Migrations \ Migration;
类UpdateTableCharset扩展了迁移{
/**
* Run the migrations.
*
* @return void
*/
public function up() {
DB::unprepared('ALTER TABLE `table_name` CONVERT TO CHARACTER SET utf8mb4');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
DB::unprepared('ALTER TABLE `table_name` CONVERT TO CHARACTER SET utf8');
}
}
注意:您仍然必须将数据库配置保留为utf8mb4
希望这对您有帮助