【问题标题】:What would be the most efficient way to load data from database in Laravel 5.4?在 Laravel 5.4 中从数据库加载数据的最有效方法是什么?
【发布时间】:2017-11-18 07:43:53
【问题描述】:

我的数据库 (PostgreSQL) 中有这些表:

events(id, title, starts_at, ends_at, ...)
reservations(id, event_id, ...)
reservation_messages(id, reservation_id, ...)

我有 API 调用:/api/v1/host/events,它必须返回一个 json 事件数组,但数组中的每个 json 对象必须包含两个附加字段 reservations_countunread_messages_count。另外我只需要未结束的事件,这意味着ends_at 列大于now()

我正在考虑加载这些“计数”字段的最有效方法。 下一个查询给了我想要的结果,但我不知道它的效率如何:

$user->host->events()
    ->where('ends_at', '>', Carbon::now())
    ->withCount([
        'reservations', 
        'reservationMessages AS unread_messages' => function($query) { 
            $query->where('seen', false); 
        }
    ])
    ->get()

这会产生很大的查询,并且会有很多连接:

select "events".*, (select count(*) from "reservations" where "events"."id" = "reservations"."event_id") as "reservations_count", (select count(*) from "reservation_messages" inner join "reservations" on "reservations"."id" = "reservation_messages"."reservation_id" where "events"."id" = "reservations"."event_id" and "seen" = ?) as "unread_messages_count" from "events" where "events"."host_id" = ? and ("events"."host_id") is not null and "ends_at" > ? and ("events"."deleted_at") is null

有没有更有效的方法来加载所需的结果,因为我认为这个查询在有大量数据的数据库上会很慢?

【问题讨论】:

    标签: sql postgresql laravel-5 query-optimization


    【解决方案1】:

    您可以在关系之间使用 with() 将查询链接在一起,以便快速加载。如果您担心数据库大小和执行时间,只需在您在集合中检索记录后对记录进行计数,并附加一个动态属性,其中包含保留计数和未读消息计数。在内存中处理集合速度很快,并且为您节省了数据库查询。

    【讨论】:

      猜你喜欢
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      相关资源
      最近更新 更多