Home > Mobile >  Laravel Foreign Key can't find Primary Key of another table through constrained() if id is name
Laravel Foreign Key can't find Primary Key of another table through constrained() if id is name

Time:03-02

So. I have searched for this problem in depth and haven't found a solution, but I solved it by mistake.

table users:

$table->id('user_id'); // I want it to be named like that specifically let's say I'm a maniac.

table whatever:

$table->foreignId('user_id')->constrained('users');

//now this should work, but it doesn't, the error seems to be that it is looking in "users" table for id instead of user_id.

What I've done is this: constrained('users', 'user_id')

//now I can't seem to find any documentation on this, to know exactly if it's OK, but it works.

I want to add that I'm a novice in programming, so the question is, is this ok to leave like this? or should I do it the old way: ->references('user_id')->on('users') ?

CodePudding user response:

Take a look at what the constrained function do behind the scenes:

public function constrained($table = null, $column = 'id')
{
   return $this->references($column)->on($table ?? Str::plural(Str::beforeLast($this->name, '_'.$column)));
}

it actually using the same old way.

you can notice that the default value for the id column going to be 'id' if not provided, so the right answer will be, passing the custom id column as the second parameter will solve this issue.

In short, you did it right

  • Related