Laravel 中的 BelongsTo 和 HasOne 有什么区别
任何机构都可以告诉我
之间的主要区别是什么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.
相关文章