我想在 Vue.js 的表列表中显示用户名而不是 supervisor_id。这是一对多的关系。supervisor_id 是来自用户表的外键。
/// 这是 vue.js 中的视图。我想将 work.supervisor_id 更改为 work.user.name 之类的内容,但它不起作用。
<tr v-for="(work,index) in works.data" :key="work.work_id">
<td>{{index+1}}</td>
<td>{{work.work_name}}</td>
<td>{{work.supervisor_id}}</td>
<td>{{work.payment}}</td>
<td>{{work.created_at | myDate}}</td>
<td>{{work.end_date}}</td>
<td>{{work.worker_id}}</td>
<td>
/// 这是我在 vue.js 中的脚本
<script>
export default {
data() {
return{
editmode: false,
works:{},
index:1,
users:{},
form: new Form({
work_id:'',
work_name:'',
description:'',
payment:'',
location:'',
end_date:'',
worker_id:'',
application_status:'New',
supervisor_id:'',
})
}
},
methods:{
getResults(page = 1) {
axios.get('api/work?page=' + page)
.then(response => {
this.works = response.data;
});
},
loadWork(){
if(this.$gate.isClerk()){
// axios.get('api/work').then(({data})=>(this.works = data));
axios.get('api/work').then(response => (this.works = response.data));
}
},
/// 这是我的工作控制器
public function index()
{
return Work::latest()->paginate(10);
}
为此,它需要Work
模型上的关系来返回supervisor
您需要的记录。
这将允许您获得supervisor
's(或user
's 取决于关系)`名称。
工作模式(app\Work.php
):
public function supervisor()
{
return $this->hasOne(User::class, `supervisor_id');
}
现在在您的控制器中,您可以使用->with()
eloquent 方法来预先加载关系:
public function index()
{
return Work::with('supervisor')->latest()->paginate(10);
}
您现在应该可以使用以下命令访问 vue 中的主管名称:
{{ work.supervisor.name }}
我希望这有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句