php - Laravel:如何在帖子列表数据表中显示作者姓名
问题描述
我想在带有数据表的帖子列表中显示作者姓名(yajra)
岗位型号:
public function author()
{
return $this->belongsTo(User::class,'post_author');
}
用户模型:
public function post()
{
return $this->hasMany(Post::class,'post_author');
}
后控制器:
public function index(Request $request)
{
if ($request->ajax()) {
$data = Post::select('post_id', 'post_title', 'post_author')->get();
return Datatables::of($data)
->addColumn('action', 'backend.columns.postsColumn')->rawColumns(['action'])
->make(true);
}
return view('admin.post.index');
}
如何在列中显示作者姓名而不是数字?
index.blade.php :
columns: [
{data: 'post_id', name: 'id'},
{data: 'post_title', name: 'post_title'},
{data: 'post_author', name: 'post_author'},]
解决方案
你也可以加入你的桌子并选择用户名......
$data = Post::join('users','users.id','posts.author_id')
->select(['post_id', 'post_title', 'post_author','users.name as authorName'])
->get();
columns: [
{data: 'post_id', name: 'id'},
{data: 'post_title', name: 'post_title'},
{data: 'post_author', name: 'post_author'},
{data: 'authorName', name: 'authorName'},
]
推荐阅读
- html - Vuetify CSS 在自定义 CSS 之后加载,如果使用 extractCSS 预渲染服务器不会加载相关链接
- spring - 如何在使用 Spring 表达式语言将服务响应分配给变量之前验证服务响应是否为空数组
- python - 搜索子列表之间的匹配项
- kubernetes - 如何升级 Kubernetes 暂停容器
- r - 使用 home-brew 和 r 4.1 在 Big Sur 上安装 rcurl 失败
- html - 身体上的外部 CSS 剂量 wokr(已关闭)
- c++ - 执行shellcode时win32 c ++访问冲突
- php - 如何在测试代码时完全覆盖条件(例如 PHP 和 xdebug)
- postgresql - EF6 + PostgreSQL + SSL
- javascript - 如何在 selenium 中使用无头 Chrome 启用 JavaScript