如何解决Laravel通过关系和分页关系数据获取全部信息
我正在尝试获取所有用户及其关联的(1:n)日记。但是我想将分页添加到关联的日记中,而不是用户中
我的控制器:
public function index()
{
$users = User::with(['journal'])->orderBy('name','asc')->get();
return view('journals/journals',['users' => $users]);
}
我的刀片:
@foreach($users as $user)
<a class="list-group-item list-group-item-action" data-toggle="collapse" href="#collapse{{$user->id}}" role="button" aria-expanded="false" aria-controls="collapse{{$user->id}}">
{{$user->name}}
</a>
<div class="collapse mt-1" id="collapse{{$user->id}}">
<div class="card card-body">
<div class="list-group">
<table class="table table-sm table-hover">
<thead>
<tr>
<th scope="col">Kunde</th>
<th scope="col">Betreff</th>
<th scope="col">Leistungsart</th>
<th scope="col">Beginn</th>
<th scope="col">Ende</th>
<th scope="col">Dauer</th>
<th scope="col">Arbeitszeit</th>
</tr>
</thead>
<tbody>
@foreach($user->journal as $journal)
<tr onclick="window.location='{{route('journal.show',[$journal->id])}}'">
<th scope="row">{{$journal->customer->name}}</th>
<td>{{$journal->title}}</td>
<td>{{$journal->type}}</td>
<td>{{$journal->started}}</td>
<td>{{$journal->ended}}</td>
<td>{{$journal->duration}}</td>
<td>{{$journal->worked}}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
@endforeach
我的日记模型:
public function user(){
return $this->belongsTo('App\User','user_id','id');
}
我的用户模型:
public function journal(){
return $this->hasMany('App\Journal','id');
}
再次,我想要实现的是我可以打印出每个用户并分页他们的日记,而不是对用户分页
我真的希望有人能在那里帮助我
解决方法
在刀片中渲染
在刀片中的for每个循环日记上方,尝试放入以下内容:
@php
$paginated_journals = $user->journal()->paginate(10);
@endphp
然后,您的for-each循环应如下所示:
@foreach($paginated_journals as $journal)
...
@endforeach
在for-each循环之后,您可以输入:
$paginated_journals->links()
获取分页链接
将数据预加载到控制器中
您可以在服务器端执行相同的操作。创建一个空的自定义数组,遍历每个用户,然后向该自定义数组添加子数组:
array_push($custom_array,['user' => $user,'journals' => $user->journal()->paginate(10)])
通过这种方式,您可以将自定义数组发送到刀片,在刀片中循环,以及呈现用户数据和分页日记。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。