Laravel 身份验证::用户关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49645879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:35:55  来源:igfitidea点击:

Laravel Auth::user relationship

laravel

提问by El Hombre Sin Nombre

In Laravel, i′m trying to show relation elements between Auth::user(Users) and Departments. In Usertable i have id, name, and department_id. In Departmentstable I have idand name.

Laravel 中,我试图显示Auth::user( Users) 和Departments之间的关系元素。在User表中,我有idnamedepartment_id。在Departments表中,我有idname

In user model i create

在我创建的用户模型中

public function department()
    {
        return $this->belongsTo('App\Models\Department');
    }

Then, in blade template I try

然后,在刀片模板中我尝试

Auth::user()->department

Auth::user()->部门

But return null and doesn′t show linkeddepartments. Null is incorrect, all usershave departments. Soo, ?Any help? ?What′s wrong in relation?

但是返回 null 并且不显示链接的部门。Null 不正确,所有用户都有部门。有什么帮助吗??有什么关系?

采纳答案by Vasyl Sovyak

You should add 'department_id' as a second parameter ($foreignKey) when calling belongsTo method, because it will searching for departmento_id by default.

在调用belongsTo 方法时,您应该添加'department_id' 作为第二个参数($foreignKey),因为它默认会搜索departmento_id。

public function departamento()
{
    return $this->belongsTo('App\Models\Departamento', 'department_id');
}

Or just rename User::departamento() method to User::department()

或者只是将 User::departamento() 方法重命名为 User::department()

public function department()
{
    return $this->belongsTo('App\Models\Departamento');
}

回答by Saiful Islam

You can try this User::with('departmento')->find(Auth::id());

你可以试试这个 User::with('departmento')->find(Auth::id());

回答by Niklesh Raut

Relation works with Model. Auth uses the session it not uses relation

关系适用于模型。身份验证使用它不使用关系的会话

Use UserModel instead

改用User模型

  optional(User::find(Auth::id())->departmento)->department_name