Migration Foreign Key Vs Eloquent Relationships in Laravel

后端 未结 2 1547
情深已故
情深已故 2021-01-30 21:47

In Laravel 5.1 I can see that table column relationships can be set-up in 2 ways:

1) Defining Foreign Keys in the Migration table.

2) De

2条回答
  •  滥情空心
    2021-01-30 22:12

    Both go hand in hand. One is in-complete without the other one. If you want your relations to work properly, you need to define both of these things.

    If you have just defined the foreign key in a migration file, the relation would work just in case you write a raw query. It won't work on your models since, you haven't written anything about relations in your models.

    So, as soon as you write hasMany in one of your models, and corresponding function in the other model, only then your models know about each other, and then you can successfully query things through your model as well as in your database.

    Also note that if you have properly defined relations through hasMany and belongsTo in your models, but haven't provided foreign key in the table of the model who belongsTo other table, your relations won't work.

    In short, both are equally compulsory.

提交回复
热议问题