Laravel中BelongsTo和HasOne有什么区别 [英] What is the difference between BelongsTo And HasOne in Laravel

查看:841
本文介绍了Laravel中BelongsTo和HasOne有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁能告诉我两者之间的主要区别是什么? 口才中的 BelongsTo HasOne 关系.

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关系的逆函数. 以UserPhone模型为例.

We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone 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('App\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.

如果要使用电话"访问用户"模型,则必须在电话"模型中添加 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('App\User');
    }
}

您可以参考此链接以获取更多详细信息.

You can refer this link for more detail.

这篇关于Laravel中BelongsTo和HasOne有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆