Skip to content
Advertisement

MySQL type CHAR problem in Laravel Eloquent

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

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

I seeded the database and the following is a sample:

code: d
name: district

In tinker:

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

returns:

=>AppModelsTable1 {#3249                                
      code: "d",         
      name: "district",
  }

Here where I cannot understand:

$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:

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

Then:

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

What so far I understood column ‘code’ type juggles to integer:

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:

class Table1 extends Model { 

    public $incrementing = false;

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

...
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement