3 回答
TA贡献1911条经验 获得超7个赞
所以你想对你的关系进行分页,如果你有好的模型,我认为你可以这样做:
public function index()
{
$data = Category::where([
['slug', '=', 'interview-questions'],
['lang', '=', auth()->user()->lang],
['profile_id', '=', auth()->user()->profile_id]
])->with(
[
'questions' => function ($query) {
$query->whereNull('parent_id')->with(
[
'answer' => function ($query) {
$query->where('user_id', auth()->user()->id);
},
]
)->orderBy('position', 'ASC');
}
]
)->first();
$data = $data->questions()->paginate(15);
}
或者,您可以单独对关系数据进行分页并将其作为新变量发送:
$questions = $data->questions()->paginate(15);
如果您有任何错误,请在此处提供。
TA贡献1856条经验 获得超17个赞
那是因为您在错误的地方使用了分页,并且您也在使用first()- 它只获取它从过滤器中找到的第一个数据。将您的代码更改为:
public function index(){
$data = Category::where([
['slug', '=', 'interview-questions'],
['lang', '=', auth()->user()->lang],
['profile_id', '=', auth()->user()->profile_id]
])->with(
[
'questions' => function ($query) {
$query->whereNull('parent_id')->with(
[
'answer' => function ($query) {
$query->where('user_id', auth()->user()->id);
},
]
)->orderBy('position', 'ASC');
}
]
)->paginate(15);
}
未经测试,但应该给你想要的结果。如果您有任何错误,请告诉我。
TA贡献1836条经验 获得超4个赞
您不能使用带有分页的first()或get()方法,因为分页本身会获取您作为参数给出的结果数(限制)。即对于您的情况,它将获取前 15 个结果并相应地分页。在访问其他页面时,它只是添加了限制的偏移量。
下面是一个示例代码。注意:分页将应用于类别,而不是问题。
public function index(){
$data = Category::where([
['slug', '=', 'interview-questions'],
['lang', '=', auth()->user()->lang],
['profile_id', '=', auth()->user()->profile_id]
])->with([
'questions' => function ($query) {
$query->whereNull('parent_id')->with([
'answer' => function ($query) {
$query->where('user_id', auth()->user()->id);
},
])->orderBy('position', 'ASC');
}
])->paginate(15);
}
- 3 回答
- 0 关注
- 382 浏览
添加回答
举报