I
I
itcoder2014-12-16 10:15:35
PHP
itcoder, 2014-12-16 10:15:35

Where is the best place to put a long sql in a project?

Available:
- php MVC self-written framework for the project.
- DB (PostgreeSql)
The project often uses complex selections with LEFT JOIN and aggregate functions, nested queries and MATERIALIZED VIEW.
From QueryBuilder it was decided to refuse, with such long queries it seemed difficult to use it.
We use PDO.
Advise in what place it is better to take out the SQL code, with subsequent convenient access to it, so as not to write it in the controller or not to inflate the models with functions in which SQL will be written?
Code example:

WITH events AS (SELECT "id","time","Seria__id","url","Event_Type__id" 
FROM "event" WHERE "time">? AND "Event_Status__id"=?)
                   SELECT "e"."id" AS "event.id",
                    min("e"."time") AS "event.time",
                    min("e"."Seria__id") AS "event.Seria__id",
                    min("e"."Event_Type__id") AS "event.Event_Type__id",
                    min("e"."url") AS "event.url",
                    array_to_string(array_agg("p"."name" ORDER BY "e_p"."owner" DESC),?) AS "partaker.name",
                    array_to_string(array_agg("p"."orig_url" ORDER BY "e_p"."owner" DESC),?) AS "partaker.orig_url",
                    array_to_string(array_agg("p"."small_url" ORDER BY "e_p"."owner" DESC),?) AS "partaker.small_url",
                    min("p_e"."price_rub") AS "product_event.price_rub",
                    min("p_e"."analytics") AS "product_event.analytics",
                    min("p_e"."id") AS "product_event.id",
                    min("o"."id") AS "order.id"
                FROM "events" "e"
                LEFT JOIN "event_partaker" "e_p"
                    ON "e"."id"="e_p"."Event__id"
                LEFT JOIN "partaker" "p"
                    ON "p"."id"="e_p"."Partaker__id"
                LEFT JOIN "product_event" "p_e"
                    ON "e"."id"="p_e"."Event__id"
                LEFT JOIN "order" "o"
                    ON ("o"."model_id"="p_e"."id" AND "model_name"=? AND "paid"=1 AND "User__id"=?)
                WHERE "p_e"."active"=1
                GROUP BY 1
                ORDER BY "event.time

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Mironov, 2014-12-16
@MironovDV

As an option Table Data Gateway

S
Sharov Dmitry, 2014-12-16
@vlom88

As an option, put it in a separate file in which there will be requests and define each request as a regular string constant

F
FanatPHP, 2014-12-16
@FanatPHP

not to inflate models with functions in which SQL will be written?

Do I understand correctly that this phrase implies that
a) some other entity needs to be inflated?
b) is it assumed that for SQL queries there is a more appropriate entity than the model?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question