gpt4 book ai didi

database - 如何使用带过滤器的 laravel 分页

转载 作者:搜寻专家 更新时间:2023-10-30 23:28:42 25 4
gpt4 key购买 nike

我在帖子模型中有 getCanSeeAttribute 函数,我尝试使用 filter() 获取带有分页的帖子

$posts = Post::where(function ($query1) use ($users) {
$query1->where('posted_type', 'user')->whereIn('posted_id', $users);
})
->orWhere(function ($query2) use ($stores) {
$query2->where('posted_type', 'store')->whereIn('posted_id', $stores);
})
->with('likes', 'postable')
->withCount('comments', 'likes')
->latest()->paginate($paginate)->filter(function($post){
return $post->can_see == true;
});

问题是当我使用过滤器时,它只获取数据属性,但我需要所有分页属性。

first_page_url": "http://localhost:8000/api/timeline?page=1",
"from": 1,
"last_page": 1,
"last_page_url": "http://localhost:8000/api/timeline?page=1",
"next_page_url": null,
"path": "http://localhost:8000/api/timeline",
"per_page": 10,
"prev_page_url": null,
"to": 6,
"total": 6

can_see not column in table it is Accessor

最佳答案

首先,我希望你知道你在做什么。假设您需要获得将 can_see 字段设置为 true 的结果,您应该使用:

$posts = Post::where('can_see', true)
->where(function($q) {
$q->where(function ($query1) use ($users) {
$query1->where('posted_type', 'user')->whereIn('posted_id', $users);
})->orWhere(function ($query2) use ($stores) {
$query2->where('posted_type', 'store')->whereIn('posted_id', $stores);
})
})->with('likes', 'postable')
->withCount('comments', 'likes')
->latest()
->paginate($paginate);

如您所见,我在额外的 where 闭包中额外包装了 (where .. orWhere) 以确保生成有效的查询。

否则你应该使用:

$posts = Post::where(function($q) {
$q->where(function ($query1) use ($users) {
$query1->where('posted_type', 'user')->whereIn('posted_id', $users);
})->orWhere(function ($query2) use ($stores) {
$query2->where('posted_type', 'store')->whereIn('posted_id', $stores);
})
})->with('likes', 'postable')
->withCount('comments', 'likes')
->latest()
->paginate($paginate);

$posts = $posts->setCollection($posts->getCollection()->filter(function($post){
return $post->can_see == true;
})
);

但是,在您的情况下,第二种方法不太可能更好。假设您有 100 万条匹配记录,然后其中的 can_see 设置为 true,其余的设置为 false,这将导致您将从数据库中获取 100 万条记录,然后您将仅过滤其中的 10 个,这对您的应用程序来说是性能 killer 。

关于database - 如何使用带过滤器的 laravel 分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52501527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com