使用 Eloquent 模型的数据类型不匹配
Posted
技术标签:
【中文标题】使用 Eloquent 模型的数据类型不匹配【英文标题】:Datatype mismatch using Eloquent Model 【发布时间】:2021-08-18 16:09:55 【问题描述】: Laravel 版本:8.44.0 php 版本:7.4.19 数据库驱动程序和版本:带有 pgBouncer 的 PostgreSQL 13.3说明:
在 PostgreSQL 数据库上使用 save()
方法和 \PDO::ATTR_EMULATE_PREPARES => true
时,DB 连接在 prepareBindings 和 bindValues 方法中将布尔值转换为整数。
复制步骤:
User::create([
'name' => 'Laravel user',
'password' => 'password',
'is_suspended' => false,
]);
错误:SQLSTATE[42804]: Datatype mismatch: 7 ERROR: column "is_suspended" is of type boolean but expression is of type integer
【问题讨论】:
玩具试过 protected $casts = [ 'is_suspended' => 'boolean', ];在你的模型中 已经试过了。不工作 为我工作:Laravel 8.36.2 Php 7.5.3 Postgresql 12.7 PgBouncer No 【参考方案1】:这是 PHP8、Laravel 8 和 PostgreSQL 上的一个已知问题。
如果您使用'false'
或'true'
或'1'
或'0'
,它会起作用。
但是,我不会依赖这样的解决方案,所以最一致的解决方案是这个
User::create([
'name' => 'Laravel user',
'password' => 'password',
'is_suspended' => DB::raw('false'), // now you're not replying on PHP to do anything, instead doing it the database way
]);
确保在顶部导入DB
Facade
use Illuminate\Support\Facades\DB;
【讨论】:
以上是关于使用 Eloquent 模型的数据类型不匹配的主要内容,如果未能解决你的问题,请参考以下文章
PHP使用组件构建自己的PHP框架使用 Eloquent 模型进行数据库操作