简体   繁体   中英

Laravel Foreign Key can't find Primary Key of another table through constrained() if id is named manually

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')?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM