Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

devamit2018's avatar

Foreign Key migration

I have 3 tables in pgsql .1.users table with column as name,email and client_id. 2. countries table with columns as name,client_id 3.students table with columns as name and client_id. can i make foreign key from users table client_id field to countries and students linked to client_id.If not what can be the best way to achieve eloquent relationship to fetch client id of users table to countries and students...i just need users table data fetched to several tables linked by clientid..

0 likes
3 replies
Nakov's avatar

So is client_id an id from the user?

Then in your User model you can add:

public function students()
{
	return $this->hasMany(Student::class, 'client_id');
}

Do the same for Countries

then:

$users = User::with('students', 'countries')->get();

foreach ($users as $user) 
{
	dd($user->students);
}
devamit2018's avatar

@Nakov Do i need to add forign key constarint to both the table students and countries or simply with model it will fetch?

Nakov's avatar
Nakov
Best Answer
Level 73

@devamit2018 it will fetch just with the model, but for performance and reliability it is good to have the foreign keys.. if you use Laravel > 8 version then this :

$table->foreignId('client_id')->constrained('users')->cascadeOnDelete();

will do the job :)

P.S. I won't name it client_id when referencing users table, but if that makes sense to you, that's the way to do it.

Please or to participate in this conversation.