我应该在 Laravel 中使用belongsTo 还是hasOne?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30058949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:30:10  来源:igfitidea点击:

Should i use belongsTo or hasOne in Laravel?

laravel

提问by wolfgang

Consider two models Aand B

考虑两个模型AB

A-> relatedTo Bis a one to onerelationship

A-> relatedToB是一个one to one关系

What is the difference in using (A ->hasOne-- B) and (A ->belongsTo-- B)?

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

Can I use them interchangeably?

我可以互换使用它们吗?

回答by user1669496

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

不,区别取决于您的外键在哪里。

In your example, if Ahas a b_idcolumn, then AbelongsToB.

在您的示例中,如果A有一b_id列,则AbelongsToB.

If Bhas an a_idcolumn, then AhasOneor hasManyBdepending on how many Bshould have.

如果Ba_id列,则AhasOnehasManyB取决于B应该有多少列。

回答by Abid Ali

Main difference is as below:

主要区别如下:

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

belongsTo并且belongsToMany- 你告诉 Laravel 这个表包含将它连接到另一个表的外键。

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

hasOne并且hasMany- 你告诉 Laravel 这个表没有外键。