1

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

迁移: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() 生成正确的查询?

提前致谢。

4

1 回答 1

1

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

class Table1 extends Model { 

    public $incrementing = false;

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

...
}
于 2020-12-26T13:00:36.060 回答