mardi 2 mai 2017

How can I write this query using the laravel query builder?

I'm on laravel 5.1 using postgres as the DB. I have a fiddle here in case it helps understand my issue: http://ift.tt/2qqbEJZ

with properties as (
    select 
        properties.*, 
        json_agg(property_fields.*) as property_fields 
    from 
        properties 
    left join fields as property_fields 
        on property_fields.parent = 'property' and property_fields.parent_id = properties.id 
    group by properties.id, properties.deal_id, properties.address
)

select 
    deals.*, 
    json_agg(properties.*) as deal_properties, 
    json_agg(deal_fields.*) as deal_fields
from deals

left join properties on deals.id = properties.deal_id
left join fields deal_fields on deal_fields.parent = 'deal' and deal_fields.parent_id = deals.id

group by deals.id, deals.name
order by deals.id

Writing most of this is fairly straight forward. The problem I'm having is with the with properties as (...) block. I've tried something like:

DB::statement('WITH properties AS ( ... )')
    ->table('deals')
    ->select(' deals.*, json_agg(properties.*) as deal_properties,  ')
    ...
    ->get();

But I notice the execution stop after DB::statement()

Is there a method in the Query Builder that I'm missing? How can I prefix my query with the WITH properties AS (...) statement?

I think it should also be noted that I'm trying to implement a Repository Pattern and I can't just wrap a DB::statement() around the whole query.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire