首页 > 解决方案 > How to get the user name by not primary key field in laravel

问题描述

I have two tables as the following

USERS
--------------
id   name
--------------
1    Joe
2    Adam
--------------


TASKS
--------------------------------------------------------
id   user_id   assigned_to   content     
--------------------------------------------------------
1       1               1     bla_bla_a
1       1               2     bla_bla_b
--------------------------------------------------------

CONTROLLER

$tasks = Task::all();
return view('list', compact('tasks'));

VIEW


<tr>
    <th>ID</th>
    <th>Creator</th>
    <th>ASSIGNED TO</th>
    <th>CONTENT</th>
</tr>

@foreach($tasks as $task)
<tr>
    {{ $task->id }}
    {{ $task->user->name }}
    {{ $task->assigend_to }}  // what sould i write here to get the user name.
    {{ $task->content }}
</tr>
@endforeach

My question is: what should i do to get the user name which task is assigned to in the view? Regards

标签: laravel-5

解决方案


使用一对一的关系。在这里阅读

Task.php模型中添加此关系

public function user() {
    return $this->belongsTo(User::class);
}

现在$task->user()->name;在 View 中获取

如果您在模型中已经有这种关系,那么只需通过以下方式急切地加载用户任务:

控制器的变化 -

$tasks = Task::with('user')->get();

推荐阅读