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

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

问题描述

任何机构都可以告诉我
之间的主要区别是什么BelongsToHasOneeloquent 中的关系.

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('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 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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