谁能告诉我这两者的主要区别是什么

推荐答案

BelongsTo与HasOne相反.

We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models.

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.

But it is not possible with Inverse process using HasOne. Like Access User model using Phone model.

如果我想使用手机访问用户模型,那么有必要在手机模型中添加BelongsTo.

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相关问答推荐

try 编写一个函数,如果产品存在,则无法删除特定类别

无法找到用户sail:passwd 文件中没有匹配的条目

如何为 CMP 横幅安装谷歌同意脚本?

使用 App::environment() 与 app()->environment() 与 config('app.env') 之间的区别

Laravel Homestead vagrant up 超时

如何为路由 laravel 5 使用OR中间件

Laravel,没有shell 访问的转储自动加载

Laravel 5表单请求验证返回禁止错误

为什么我的 Laravel 队列作业(job)在 60 秒后失败?

在 laravel 5.2 中禁用特定路由的 Web 中间件

路由模型绑定不起作用

Laravel - 自定义时间戳列名称

Http请求多浏览器的烦恼

如何在 Laravel 中实现数组类型路由?

如何在 Laravel 5 中按键获取所有缓存项目的列表?

Laravel 字符串验证以允许空字符串

Laravel homestead IP地址不起作用

count() 参数必须是数组或在 laravel 中实现可数的对象

phpunit 命令不适用于 Windows 7 上的 laravel 4

有没有办法让表名自动添加到 Eloquent 查询方法中?