我使用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試過,但它不起作用。 –