MySQL Laravel 中的 CHAR 类型问题 Eloquent

MySQL type CHAR problem in Laravel Eloquent

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

迁移:create_table1_table

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

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

code: d
name: district

在修补程序中:

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

returns:

=>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();

Returns:

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).

到目前为止我理解的内容列 'code' 将 juggles 键入整数:

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

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

提前致谢。

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

class Table1 extends Model { 

    public $incrementing = false;

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

...
}