首页 > 解决方案 > Laravel/Eloquent 分页和 groupBy 用于 postgres 物化视图模型

问题描述

我创建了一个物化视图:accounts_index它有几个左连接,所以我需要使用 eloquent 模型进行分组。我还需要对集合进行分页,并且无法确定事物的顺序。物化视图:

CREATE materialized VIEW accounts_index
        AS SELECT a.account_uuid,
                  a.account_no,
                  a.person_owner_uuid,
                  a.company_owner_uuid,
                  a.account_group_uuid,
                  a.account_scope_uuid,
                  a.created_at,
                  a.deleted_at,
                  s.service_uuid,
                  s.status,
                  st.service_type
        FROM   accounts a
                LEFT JOIN services s
                        ON a.account_uuid = s.account_uuid
                LEFT JOIN service_types st
                        ON s.service_type_uuid = st.service_type_uuid

雄辩的模型可以像这样抓住这张桌子:AccountIndex::all();. 我可以对它进行分页:AccountIndex::paginate();或做一个 groupBy: AccountIndex::all()->groupBy('account_uuid');,但不知道如何将两者结合起来。一些尝试:

我要解决的主要问题是这些联接将返回具有多个服务(所以多行)的帐户,然后我需要按account_uuid. 提前感谢您的任何见解!

标签: laravelpostgresqleloquentlaravel-5.8materialized-views

解决方案


几乎

AccountIndex::groupBy('account_uuid')->paginate()

分页实际上做了一些事情

groupBy()只是像编写 SQL 一样编写 SQL ->where() ->join(),所有这些都准备了一条 SQL 语句,您可以通过运行来尝试->toSql()返回一个 sql 字符串。

get() all() paginate()所有人实际上都在做某事,例如执行 SQL。


推荐阅读