首页 > 解决方案 > 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'},]

标签: phplaraveldatatablesrelation

解决方案


你也可以加入你的桌子并选择用户名......

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

推荐阅读