laravel - 需要在 vue.js 前端和 Laravel 后端打印名称而不是 id
问题描述
这是我的 CategoryController.php 代码...
public function name($id) {
$f = Category::findOrFail($id);
$nm = $f->name;
return $nm;
}
这是我的路由器。
Route::get('/category/{id}', [CategoryController::class, 'name']);
在 vue.js 我在方法中定义了这个,
async getCategoryName($id){
await this.callApi('get','/category/' + $id)
.then(response => {
this.name = response.data.name
return this.name;
});
}
在表中,我需要获取类别名称而不是类别 ID。从 URL 我得到类别名称,但它表明 [object promise]
<table class="_table">
<!-- TABLE TITLE -->
<tr>
<th>ID</th>
<th>Category Name</th>
<th>Name</th>
<th>Created At</th>
<th>Action</th>
</tr>
<!-- TABLE TITLE -->
<!-- ITEMS -->
<tr v-for="(tag, i) in tags" :key="i" if="tags.length">
<td>{{tag.id}}</td>
<td>{{getCategoryName(tag.categoryId)}}</td>
<td class="_table_name">{{tag.name}}</td>
<td>{{tag.created_at}}</td>
<td>
<Button type="info" size="small" @click="showEditModal(tag, i)">Edit</Button>
<Button type="error" size="small" @click="showDeletingModal(tag, i)" :loading="tag.isDeleting">Delete</Button>
</td>
</tr>
</table>
请帮我...
解决方案
这是 vue.js 的正常行为,为什么不在控制器中添加类别名称而不是在服务器端加载它,您的方法在性能方面并不好。
在您获得视图的控制器中,您将拥有以下内容:$tags = Tag::all()
您可以简单地加载每个类别:$tags = Tag::with('category')->get()
在您的 vue 应用程序中,您可以简单地访问名称,例如:tag.category.name
推荐阅读
- html - 花哨的盒子和网格显示问题。图片重叠
- sql - SQL 连接和将 1 列引入 2 列
- r - R中的热图失败
- r - 在 R 中:我可以将行号 =1 的数据框(例如 x)分配为另一个数据框(例如 y)的列标题吗?
- vb.net - 有人可以帮我理解 Visual Basic 中的数据表计算功能吗?
- firebase - 如何在 Flutter 中加入来自两个 Firestore 集合的数据?
- javascript - Firebase 在 for 循环中添加
- angular - Angular 9 按日期对项目进行分组
- casting - Python中的数据类型转换和映射对象错误,TypeError: a bytes-like object is required, not 'map'
- powershell - 如何修复此 Powershell FTP 上传错误