spatie / laravel-query-builder

Easily build Eloquent queries from API requests
https://spatie.be/docs/laravel-query-builder
MIT License
4k stars 392 forks source link

whereJsonContains is not working #919

Closed doraemonxxx closed 5 months ago

doraemonxxx commented 7 months ago

whereJsonContains is not working even though you debug it and make it raw sql using toSql() method

alexrififi commented 5 months ago

Show me code!

doraemonxxx commented 5 months ago

I apologize for the delay in responding. Due to other commitments, I won't be able to provide the code for replication at the moment. I'll close this ticket for now and may open a new one in the future. Thank you.

djamesfar commented 6 days ago

I have this problem as well. Using laravel-query-builder v5, Laravel 11 Here's my AllowedFilters:

            ->allowedFilters([
                AllowedFilter::partial('customer', 'contact_name'),
                AllowedFilter::exact('number', 'id'),
                AllowedFilter::exact('status', 'rma_status_id'),
                AllowedFilter::callback('part', function(\Illuminate\Database\Eloquent\Builder $query, $value) {
                    $query->whereHas('details', function($q) use ($value) {
                        $q->where('part_id', $value);
                    });
                }),
                AllowedFilter::callback('serial_number', function(\Illuminate\Database\Eloquent\Builder $query, $value) {
                    $query->whereHas('details', function($q) use ($value) {
                        $q->whereJsonContains('serial_numbers', $value);
                    });
                }),
            ])

The problem is the last filter, 'serial_number' callback function. It is supposed to return all RMAs that contain RMA details (Rma 'details' relation) whose 'serial_numbers' json array contains the supplied serial_number ($value). RmaDetail model casts 'serial_numbers' as array.

This works fine in tinker:

$rmas = Rma::whereHas('details', function($q) use ($sn) { $q->whereJsonContains('serial_numbers', 'MN220518063'); })->get()

In tinker, this correctly returns the RMA record that contains an RmaDetail with serial_numbers json field that contains the supplied serial number.

Anything I'm doing wrong here?