Should i use belongsTo or hasOne in Laravel?

后端 未结 3 1414
深忆病人
深忆病人 2020-12-12 12:51

Consider two models A and B

A -> relatedTo B is a one to one relationship

What is the differ

相关标签:
3条回答
  • 2020-12-12 13:36

    Main difference is as below:

    belongsTo and belongsToMany - you're telling Laravel that this table holds the foreign key that connects it to the other table.

    hasOne and hasMany - you're telling Laravel that this table does not have the foreign key.

    0 讨论(0)
  • 2020-12-12 13:37

    The model who's table contains the foreign key will have belongsTo() in it while the model who's table contains that primary key to which that foreign key is referencing to will have hasOne()... its easy the model that has the foreign key will have belongsTo() and the one that doesn't contain the foreign Key in that relationship will have hasOne(). and no they are not interchangeable using the wrong method will always return null as a result.

    0 讨论(0)
  • 2020-12-12 13:40

    No, the difference depends on where your foreign key is.

    In your example, if A has a b_id column, then A belongsTo B.

    If B has an a_id column, then A hasOne or hasMany B depending on how many B should have.

    0 讨论(0)
提交回复
热议问题