私はthis repoを私のプロジェクトの出発点として使用しています。Laravel 5.4関連データを取得して表示する
私はuser
テーブルとclubs
テーブルを持っています。 User
は1つのクラブを持つことができ、にはclub
が割り当てられます。
したがって、hasOne
の関係をclubs
テーブルに定義しました。
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);
}
public function getForDataTable()
{
return $this->query()
->with('user')
->select([
'clubs.id',
'clubs.clubName',
'clubs.description',
'clubs.user_id',
'clubs.created_at',
'clubs.updated_at',
]);
}
私の 'getFromDataTable()' メソッドである私の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>
を下回っている私はここで間違って何をしているのですか?クラブテーブルは、それがユーザーをbelongs to
意味USER_ID列を、持っている場合、ない -
@AaronFaheyはそれを試みましたが、それは動作しませんでした。 –