2017-06-15 15 views
0

私は私のデータベース(PostgreSQLの)中で、これらのテーブルを持っている:Laravel 5.4のデータベースからデータをロードする最も効率的な方法は何でしょうか?

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

そして私は、APIの呼び出しがあります。/api/v1/host/eventsイベントのJSON配列を返す必要がありますが、配列内の各JSONオブジェクトは、2つの追加フィールドが含まれている必要がありreservations_countunread_messages_count 。また、私は終了していないイベントのみが必要です。つまり、列が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 

はこれ以上あります私はこのクエリがそれに多くのデータを持つデータベースで非常に遅いと思うので、望ましい結果をロードする効率的な方法?

答えて

0

リレーションシップの間にwith()を使用すると、クエリを連鎖させることができます。また、データベースのサイズと実行時間が懸念される場合は、コレクション内でレコードを取得した後、レコードの数をカウントし、予約数と未読メッセージ数の動的プロパティを追加してください。メモリ内のコレクションの作業は高速で、DBクエリーは不要です。

関連する問題