我应该在 Laravel 使用 belsto 还是 hasOne?

考虑两种型号 AB

B相关的是 one to one关系

使用(A-> hasOne-B)和(A-> belongsTo-B)有什么区别?

我可以互换使用它们吗?

40759 次浏览

不,差异取决于您的外键在哪里。

在您的示例中,如果 A有一个 b_id列,那么 A belongsTo B

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

主要区别如下:

belongsTobelongsToMany-你是在告诉 Laravel 这个表拥有连接它和另一个表的外键。

hasOnehasMany-你告诉 Laravel 这个表没有外键。

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.

这与外键在哪里无关。

OP 提出了两种情况: A hasOne B,A belongsTo B

对于上下文示例,让 A = user 和 B = company。

你可以说“ user own (hasOne) a company”,反过来也可以说“ user worksAt (belongsTo) a company”。

在这两种情况下,user都有一个 company_id字段

Please let that sink in for a moment. Thus, discussing the location of foreign key is a non starter. The most apt answer can be found here: Https://laravel.io/forum/04-20-2015-belongsto-vs-hasone

虽然它有效,但它是对这种关系的不正确描述。

回答观察员的问题: 不,你不应该互换使用它们

它们通常成对使用

  1. A belongsToB B hasManyA
  2. B belongsTo A,A hasMany B
  3. A hasOne B,B hasMany A <-这将导致与双方使用 hasXXX的问题,见链接。

"BelongsTo" goes in the table with the "xxx_id" column. 例如: 国家有城市。 City 属于 Country (City 表中的 Country _ id)。 另一个例子: 一张脸只有一个鼻子。 鼻子属于一张脸(鼻子表中的 face _ id)。

hasOnebelongsTo之间的唯一区别是外键列所在的位置。

假设有两个实体: 用户帐户

如果 users表具有 account_id列,则 用户 belongsTo 帐户。(和 帐户无论是 hasOnehasMany 用户)

但是,如果 users表没有 account_id列,而 accounts表有 user_id列,那么 用户 hasOnehasMany 帐目