1

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:

=>App\Models\Table1 {#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.

1 Answer 1

1

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'
    ];

...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Repox for the amazing help. Problem solved. In additon to Repox's solution, I also added: protected $keyType = 'string';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.