我应该在 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
Should i use belongsTo or hasOne in Laravel?
提问by wolfgang
Consider two models A
and B
考虑两个模型A
和B
A
-> relatedTo B
is a one to one
relationship
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 A
has a b_id
column, then A
belongsTo
B
.
在您的示例中,如果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.
如果B
有a_id
列,则A
hasOne
或hasMany
B
取决于B
应该有多少列。
回答by Abid Ali
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.
belongsTo
并且belongsToMany
- 你告诉 Laravel 这个表包含将它连接到另一个表的外键。
hasOne
and hasMany
- you're telling Laravel that this table does not have the foreign key.
hasOne
并且hasMany
- 你告诉 Laravel 这个表没有外键。