skip to Main Content

I have a simple json table containing an array of values:

[1,2,3,4,5,6,7,8,9]

I’m trying to query this table by multiple conditions:

  1. Must contain the value 2
  2. Must contain atleast 3 of the other values, it does not matter which ones

This is what I currently have:

$data= Model::whereJsonContains('my_column', [2])->get();

This works for condition 1, now I can’t seem to figure out how to include condition 2 as well.

2

Answers


  1. $data = Model::whereJsonContains('my_column', 2)
    ->where(function ($query) {
        $query->whereJsonContains('my_column', 1)
            ->orWhereJsonContains('my_column', 3);
            
    })
    ->get();
    
    Login or Signup to reply.
  2. Assuming your JSON array has unique values, you can use whereJsonLength to count the size of the JSON array like below:

    $data = Model::whereJsonContains('my_column', 2)
                  ->whereJsonLength('my_column', '>', 3)
                  ->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search