laravel-5 - 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
解决方案
使用一对一的关系。在这里阅读
在Task.php模型中添加此关系
public function user() {
return $this->belongsTo(User::class);
}
现在$task->user()->name;
在 View 中获取
如果您在模型中已经有这种关系,那么只需通过以下方式急切地加载用户任务:
控制器的变化 -
$tasks = Task::with('user')->get();
推荐阅读
- jenkins - 将质量门添加到 Jenkins Maven 项目的构建部分
- javascript - 推送新的动态 URL 时,React Router 不会重新呈现同一页面
- npm - 是否可以将项目的 node_modules 存档,然后将其上传到 Nexus Repository Manager?
- javascript - 如何解决 Codility equiLeader 挑战
- type-conversion - 在 Julia 中绘制 ForwardDiff 的输出
- xml - XSLT 1.0 - 基于来自不同节点的属性值创建节点
- javascript - 如何在json文件javascript中写入数据而不是在节点js中
- javascript - 带有 Electron 的 TestCafe 抛出“未捕获的类型错误:无法读取未定义的属性‘源’”
- xml - Jaxb:验证子元素
- javascript - 如何在承诺中添加超时?