問題描述
任何機構都可以告訴我
之間的主要區別是什么BelongsTo 和 HasOne 在 eloquent 中的關系.
Can any body tell me what is the main difference between
the BelongsTo and HasOne relationship in eloquent.
推薦答案
BelongsTo 是 HasOne 的逆.
BelongsTo is a inverse of HasOne.
我們可以使用belongsTo 方法定義hasOne 關系的逆.以 User
和 Phone
模型為例.
We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with
User
andPhone
models.
我給出了從用戶到電話的 hasOne 關系.
I'm giving hasOne relation from User to Phone.
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('AppPhone');
}
}
使用這種關系,我可以使用 User 模型獲取 Phone 模型數據.
Using this relation, I'm able to get Phone model data using User model.
但是使用 HasOne 的逆過程是不可能的.就像使用電話模型訪問用戶模型一樣.
But it is not possible with Inverse process using HasOne. Like Access User model using Phone model.
如果我想使用Phone訪問User模型,則需要在Phone模型中添加BelongsTo.
If I want to access User model using Phone, then it is necessary to add BelongsTo in Phone model.
class Phone extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo('AppUser');
}
}
您可以參考此鏈接了解更多詳情.
You can refer this link for more detail.
這篇關于Laravel 中的 BelongsTo 和 HasOne 有什么區別的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!