问题描述
我想在带有数据表(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'},]