Laravel:如何在帖子列表数据表中显示作者姓名

问题描述

我想在带有数据表(yajra)的帖子列表中显示作者姓名

发布模型:

public function author()
{
    return $this->belongsTo(User::class,'post_author');
}

用户模型:

public function post()
{
    return $this->hasMany(Post::class,'post_author');
}

PostController:

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'},]

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...