lundi 5 avril 2021

Laravel selectSub with IFNULL

I have a complex query with a correlated subquery which I would like to integrate in my Laravel application.

The problem is that the subquery is inside IFNULL.
The query is very big, I tried to write a very reduced one only for demonstration:

SELECT payment_status_id, client_tbl.client_id
    IFNULL((SELECT payment_status_id
            FROM payment_status_tbl
            WHERE payment_status_tbl.client_id = client_tbl.client_id
            ORDER BY status_date DESC
            LIMIT 1), 0) AS current_status_id
FROM client_tbl
HAVING current_status_id < 4;

I reached this query in Laravel:

$query = DB::table('client_tbl')
            ->select(['payment_status_id', 'client_tbl.client_id'])
            ->selectSub(function($query) {
                $query->select('payment_status_id')
                    ->from('payment_status_tbl')
                    ->where('payment_status_tbl.client_id', '=', 'client_tbl.client_id')
                    ->orderByDesc('status_date')
                    ->limit(1);
            }, 'current_status_id')
            ->having('current_status_id', '<', 4);

but it does not include the IFNULL statement, which is important in my original query.

Any idea whether it is possible?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire