升级Aurora MySQL后Laravel Eloquent触发JSON wrapper内部错误求助
问题背景
原本因select * from users where id IN ()触发Amazon Aurora 3.02.2(基于MySQL 8.0.23)的bug导致实例重启,按亚马逊建议升级到3.03.1(基于MySQL 8.0.26)后,重启问题解决,但多个Laravel接口查询users表时出现相同错误。
报错信息
两个接口的报错完全一致:
Illuminate\Database\QueryException · SQLSTATE[HY000]: General error: 1815 Internal error: JSON wrapper: unexpected type (SQL: select * from
userswhereusers.idin () and users.deleted_atis null)Illuminate\Database\QueryException · SQLSTATE[HY000]: General error: 1815 Internal error: JSON wrapper: unexpected type (SQL: select * from
userswherestripe_customer_ref= cus_test andusers.deleted_atis null)
相关代码
- 聊天消息关联查询代码:
// Retrieve public chat messages with sender information $publicMessages = $webinar->webinarChatMessages() ->where('type', WebinarChatMessage::TYPE_MESSAGE) ->with(['sender']) ->whereNull('recipient_id') ->orderBy('webinar_chat_messages.id', 'asc') ->get();
- Stripe用户查询代码:
$user = UserWN::where('stripe_customer_ref', $json['customer'])->get()->last();
排查情况
直接在数据库客户端执行相同SQL语句无报错,推测问题出在Laravel Eloquent与升级后Aurora MySQL的交互逻辑上。
可能的解决方向
1. 检查Laravel依赖兼容性
Aurora MySQL 3.03.1基于MySQL 8.0.26,确认Laravel框架及doctrine/dbal、illuminate/database等数据库相关依赖版本是否适配该MySQL版本,必要时升级对应依赖包。
2. 强制规范查询参数类型
报错提示JSON wrapper类型异常,大概率是Eloquent绑定参数时的类型与数据库期望不匹配:
- 对于IN查询,确保传入的ID数组为纯整数类型:
// 示例:将ID数组强制转为整数 $userIds = array_map('intval', $userIds); $users = User::whereIn('id', $userIds)->get(); - 对于字符串匹配(如
stripe_customer_ref),显式转换参数为字符串,同时优化查询方法:// 用first()替代get()->last(),减少不必要的数据集加载 $user = UserWN::where('stripe_customer_ref', (string)$json['customer'])->first();
3. 调整模型JSON字段处理逻辑
如果users表包含JSON类型字段,升级后的Aurora对JSON的处理逻辑可能有变化,可在模型中显式指定字段类型,避免Eloquent自动处理时的冲突:
// 在User模型中定义字段类型 protected $casts = [ 'your_json_field' => 'array', // 或根据实际需求设为string类型 ];
也可直接使用原生查询绕过Eloquent的自动处理:
$user = UserWN::whereRaw('stripe_customer_ref = ?', [$json['customer']])->first();
4. 重置Laravel缓存
升级数据库后,旧的查询缓存、模型元数据可能导致异常,执行以下命令清理缓存:
php artisan cache:clear php artisan config:clear php artisan route:clear
5. 检查数据库连接配置
确认config/database.php中MySQL连接的options配置,是否存在影响JSON解析的自定义参数,尝试暂时重置为默认配置测试。
内容的提问来源于stack exchange,提问作者Giuseppe87

