mardi 23 juillet 2019

How to create a complex query with sub select, count, calculated columns in laravel?

I have got this following query in SQL and I would like to create it in Laravel/Eloquent project.

The SQL query works in PostgreSql. I have already exists the Models, and DB schemas. How can I create more sub select in eloquent? This query create two calculated columns, what I would like to use in the future...

This query create 5 columns in the result: id,first_name,last_name,count_voucher,unused_count

I have already tried raw sql, but unfortunatelly the further builder modifications did not work, because the type was expression, array, or collection. I need builder type to use where and orWhere methods.

SELECT users.id, users.first_name, users.last_name, 
             (SELECT count(ph.id)
                            from users u
                            left outer join purchase p on u.id = p.user_id
                            left outer join purchase_history ph on 
                            ph.purchase_id=p.id      
                            where u.id= users.id ) as count_voucher, 
             (SELECT  count(ph.id)
                            from purchase_history ph
                            inner join purchase p on p.id = ph.purchase_id
                            inner join package on ph.package_id = ph.id     
    inner join voucher on package.voucher_id = voucher.id  
    inner join offer_main on offer_main.id = voucher.offer_main_id  
                            where p.user_id=users.id and ph.used is true 
                            and offer_main.valid_end < current_date) as 
                            unused_count
                           from users



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire