They say, if you want to find the answer, ask the right question. Really, here I don’t know what to ask. Because I don’t know what’s happening.
Migration:create_table1_table
JavaScript
x
$table->char('code', 1)->primary();
$table->string('name', 50);
I seeded the database and the following is a sample:
JavaScript
code: d
name: district
In tinker:
JavaScript
$t1 = Table1::find('d');
returns:
JavaScript
=>AppModelsTable1 {#3249
code: "d",
name: "district",
}
Here where I cannot understand:
JavaScript
$t1->code; //returns 0 <---This should be 'd'
$t1->name; //returns district
This causes my model which has a hasMany(Table2::class, ‘t1_pk’) relationship with table2 to not work correctly:
JavaScript
public function table2 () {
return $this->hasMany(Table2::class, 't1_pk');
}
Then:
JavaScript
$t1->table2()->toSql();
Returns:
JavaScript
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).
What so far I understood column ‘code’ type juggles to integer:
JavaScript
getType($t1->code); //returns Integer
What is going on here and how to make laravel’s Eloquent hasMany() to generate a correct query?
Thanks in advance.
Advertisement
Answer
You have to cast your custom primary key to the correct type and ensure that Eloquent doesn’t think that your primary key is auto incrementable:
JavaScript
class Table1 extends Model {
public $incrementing = false;
protected $casts = [
'code' => 'string'
];
}