Answer a question

there is my code:

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

    return $query;
}

There is my filter function. $room_count is array, and for example can be [2,4]. rent_requests.rooms_count is JSON array in MySQL, and it can be for example [2,3]. I need to filter this, to get this advert showed, but whereJSONContains expects that there will be 2 and 4, not 2 or 4. Is there any tricks to make this function work correctly ? Something like json contains whereIn ?) Sorry for my english, im really stuck on this, please help me :)

Answers

MySQL and PostgreSQL support whereJsonContains with multiple values:

So if you are using either of the database then you can pass $room_count as the second parameter

// 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;
      });
}

Laravel docs: https://laravel.com/docs/8.x/queries#json-where-clauses

Logo

华为、百度、京东云现已入驻,来创建你的专属开发者社区吧!

更多推荐