H
H
hesy2021-08-26 12:25:25
Laravel
hesy, 2021-08-26 12:25:25

How to search on multiple multidimensional JSON field in Eloquent Laravel?

Migration
Schema::create('examples', function (Blueprint $table) {
    ...
    $table->json('cars');
    ...
});


The content of the 'cars' field
[
   {
      "name":"Sport",
      "list":[
         {
            "id":1,
            "name":"example"
         },
         {
            "id":2,
            "name":"example"
         },
         {
            "id":3,
            "name":"example"
         }
      ]
   },
   {
      "name":"Jeep",
      "list":[
         {
            "id":4,
            "name":"example"
         },
         {
            "id":5,
            "name":"example"
         },
         {
            "id":6,
            "name":"example"
         }
      ]
   }
]


How to search on cars field and select all records where id = N ? MySQL base.

$carIds= [1, 3, 5];

// вот так работает, но только если id передать как int, с массивом $carsIds уже не работает :/
Example::whereJsonContains('cars', ['list' => ['id' => 1]])->get()

Example::whereJsonContains('cars', $carIds)->get();

// пробовал хотя бы просто найти по первому элементу 
Example::whereJsonContains('cars->0->list->0->id', $carIds)->get();

// это тоже не получилось
Example::whereJsonContains('cars->*->list->*->id', $carIds)->get();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex Wells, 2021-08-26
@Alex_Wells

Normal - nothing. And judging by the example, you need to redo the table structure.

H
hesy, 2021-08-26
@hesy

In general, I solved the problem as follows:

$carsIds = [1, 2, 5];

$example = Example::query();

foreach ($carsIds as $carId) {
    $example->whereJsonContains('cars', ['list' => ['id' => $carId]]);
}

$examples = $example->take(12)->get();

You can also use orWhereJsonContains if needed.
The loop, because it does not work with an array, although maybe I'm doing it wrong.
Example::whereJsonContains('cars', ['list' => ['id' => $carIds]])->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question