【问题标题】:How to use Laravel Collection groupBy along with Query Pagination?如何使用 Laravel Collection groupBy 和查询分页?
【发布时间】:2018-11-17 10:20:00
【问题描述】:

我喜欢使用 Laravel 的 groupBy 函数 https://laravel.com/docs/5.6/collections#method-groupby

但是,我不能将它与 paginate(x) 函数一起使用,因为它返回的结果数量有限。 SQL Query 的 Groupby 和 Laravel Collections 的 GroupBy 是完全不同的。如果我在查询中使用 groupby,它不会给我想要的东西。例如,我只想打字,我得到了我想要的。

$notifications = $notifications->groupBy('order_id');

例如这是我的查询

    $notifications = DB::table('sent_notifications as a')
        ->join('sent_notification_results as b', 'a.sent_notification_result_id', '=', 'b.sent_notification_result_id')
        ->join('orders as c', 'c.order_id', '=', 'a.order_id')
        ->join('sellers as d', 'c.seller_id', '=', 'd.seller_id')
        ->join('companies as e', 'd.company_id', '=', 'e.company_id')
        ->join('notification_templates as f', 'f.notification_template_id', '=', 'a.notification_template_id')
        ->join('notification_types as g', 'g.notification_type_id', '=', 'f.notification_type_id')
        ->join('default_notification_templates as h', 'h.default_notification_template_id', '=', 'f.default_notification_template_id')
        ->where('e.company_id', $company_id)
        ->select('*')
        ->orderBy('a.created_at','DESC')
        ->paginate(20);
    $pagination_links = $notifications->links();

如何将 Collection 的 groupby 方法与分页一起使用?

【问题讨论】:

  • 您的预期结果究竟是什么?
  • 可以添加要构建的查询吗?

标签: laravel eloquent laravel-5.6 laravel-collection laravel-pagination


【解决方案1】:

我参与了一个有类似问题的项目,并提出了这个解决方案。

public function index(Request $request)
{
    $posts = Post::all()
        ->paginate($request->get('per_page', 25));

    $grouped_by_date = $posts->mapToGroups(function ($post) {
        return [$post->published_date => $post];
    });
    $posts_by_date = $posts->setCollection($grouped_by_date);

    return view('posts.index', compact('posts_by_date'));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 2017-07-03
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多