D
D
D3V1L2020-12-04 21:14:48
Laravel
D3V1L, 2020-12-04 21:14:48

Laravel Eloquent JSON Contains, how to pass an array to a function and check for the presence of one of the elements in the database?

Hi here is my function code

protected function room_count($room_count)
{
    $query = $this->builder
        ->whereJsonContains('rent_requests.rooms_count', $room_count);

    return $query;
}


written in laravel query builder, it is a filtering function.
in the database, the rooms_count field is an array that can contain an arbitrary number of rooms:
examples: [2, 4] , [3, 2, 1], [1,2,3,4] and so on.
The same array gets into the filters, and I need to check that one of the $rooms_count elements is present in the rooms_count field in the database.
I used the JSON Contains function, everything is ok, but it checks the occurrence of all parameters, not just one of them.
That is, if I pass [2,4], the function expects that the json array will contain both 2 and 4. And I need to somehow check that if there are 2 OR 4 in the database, in the rent_requests.rooms_count field, then this model is included in the selection . Now, if there are no ALL filter values, it simply throws out this model

Has anyone else experienced this, or is there a different way to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
D3V1L, 2020-12-06
@D3V1L

Got it, here is the final solution

// Room Count Filter
protected function room_count($room_count)
{

    return $this->builder
        ->where(function($query) use($room_count){
     
            $query->whereJsonContains('rent_requests.rooms_count', $room_count[0]);
    
            for($i = 1; $i < count($room_count); $i++) {
               $query->orWhereJsonContains('rent_requests.rooms_count', $room_count[$i]);      
            }
    
            return $query;
      });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question