In Laravel it is possible to use the hasMany()
and belongsTo()
methods in the Model to specify the relation between tables. This for one-to-many relations.
However in the migration files, this relation is also specified for the database by the
$table->foreign('userId')->references('id')->on('users')
Why does it to be specified double in Laravel? Why does Laravel doesn't fetch the relationship from the database, and do we have to specify it double?
CodePudding user response:
Laravel offers hasMany()
and belongsTo()
etc for quicker access to parent/child records between tables on the model level. For instance, you may access the child record with ->{attr}
, which makes the child record as if an attribute of the parent record.
It also comes with other benefits, such as eager loading of child record by providing the relationship parameter into ->with()
function.
In comparison, the usage of relation in migration files are to enforce relationship between tables on database level.