微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Laravel Eloquent 中的 MySQL 类型 CHAR 问题

如何解决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'
    ];

...
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。