Laravel Eloquent 中的 MySQL 类型 CHAR 问题

问题描述

他们说,如果您想找到答案,请提出正确的问题。真的,在这里我不知道该问什么。因为我不知道发生了什么。

迁移:create_table1_table

$table->char('code',1)->primary();
$table->string('name',50);

我对数据库进行了播种,以下是一个示例:

code: d
name: district

修补匠:

$t1 = Table1::find('d');

返回:

=>App\Models\Table1 {#3249                                
      code: "d",name: "district",}

我无法理解的地方:

$t1->code; //returns 0 <---This should be 'd'
$t1->name; //returns district

这会导致与 table2 具有 hasMany(Table2::class,'t1_pk') 关系的模型无法正常工作:

public function table2 () {
    return $this->hasMany(Table2::class,'t1_pk');
}

那么:

$t1->table2()->tosql();

返回:

select * from `table2` where `table2`.`t1_pk` = ? and `table2`.`t1_pk` is not null

//Here the foreign key "table2.t1_pk" that must be matched with the value of "table1.code = 'd'" changes to ? (anything).

到目前为止我所理解的列“代码”类型杂耍到整数:

getType($t1->code); //returns Integer

这里发生了什么以及如何让 Laravel 的 Eloquent hasMany() 生成正确的查询

提前致谢。

解决方法

您必须将自定义主键转换为正确的类型,并确保 Eloquent 不会认为您的主键是可自动递增的:

class Table1 extends Model { 

    public $incrementing = false;

    protected $casts = [
        'code' => 'string'
    ];

...
}