1
votes

Suppose we have many to one relationship between table A and table B. Now there are two possibilities to define this relation in Laravel.

  1. while creating migration I use the "References" Keyword. and the run the migration

  2. The other way is I use hasMany and belongsTo in model class corresponding to those tables and do not mention References and all in migration tables.

Can some one help me in understanding what approach I should follow. Or we need to have both the approach in our codebase to create relationships. Can some one throw some light on it. I am kind of confused. I am new to Laravel and learning these intricacies. thank you.

2

2 Answers

2
votes

Actually, you should use both 1 and 2 to make Eloquent relations work. If you're using raw queries, you can use only 1, but the real power of Laravel is in Eloquent model relations.

Eloquent assumes the foreign key of the relationship based on the model name

https://laravel.com/docs/5.1/eloquent-relationships#defining-relationships

0
votes

You should use both the approach,

  • using references onto the migration itself leads to data integrity at database table level
  • To really explore the power of laravel one should use Eloquent and this can be achieved by establishing eloquent relationships among Models.

Reference : https://laravel.com/docs/5.2/eloquent-relationships

! Happy Coding!