我使用this repo作为我的项目的起点。Laravel 5.4获取相关数据并显示
我有一个user
表和clubs
表。 User
可以有一个俱乐部,club
连接到一个user
。
因此,我在下面的clubs
表中定义了hasOne
关系。
public function user()
{
return $this->hasOne(User::class, 'id', 'user_id');
}
clubs
表有user_id
列。
我无法在我的index
页面上获取正确的数据以显示User
的userName
。
我正在使用ClubsRepository
来显示数据。
下面是它的代码。
public function __invoke(ManageClubRequest $request)
{
return Datatables::of($this->clubs->getForDataTable())
->escapeColumns(['clubName', 'sort'])
->addColumn('user', function ($clubs) {
return $clubs->user->pluck('first_name');
})
->addColumn('actions', function ($clubs) {
return $clubs->action_buttons;
})
->withTrashed()
->make(true);
}
在下面库是我的 'getFromDataTable()' 方法
public function getForDataTable()
{
return $this->query()
->with('user')
->select([
'clubs.id',
'clubs.clubName',
'clubs.description',
'clubs.user_id',
'clubs.created_at',
'clubs.updated_at',
]);
}
我index.blade
代码如下
<table id="clubs-table" class="table">
<tr>
<th>clubName</th>
<th>description</th>
<th>userName</th>
<th>created</th>
<th>last_updated</th>
</tr>
</table>
<script>
$(function() {
$('#clubs-table').DataTable({
dom: 'lfrtip',
processing: false,
serverSide: true,
autoWidth: false,
ajax: {
url: '{{ route("admin.access.clubs.get") }}',
type: 'post',
data: {status: 1, trashed: false},
error: function (xhr, err) {
if (err === 'parsererror')
console.log(err);
}
},
columns: [
{data: 'clubName', name: 'clubs.clubName'},
{data: 'description', name: 'clubs.description'},
{data: 'user', name: 'user.first_name', sortable:false},
{data: 'created_at', name: 'clubs.created_at'},
{data: 'updated_at', name: 'clubs.updated_at'}
],
});
});
</script>
我到底做错了什么?
@AaronFahey试过,但它不起作用。 –