I've been working with Laravel 5.4's eloquent and I've encountered a problem.
I have a database table called posts and in that, a column named as template_ids
. It stores the values in json_encoded
format like:
["1","25","48"]
Now, I want to apply a filter to my query based on an array of IDs:
$id_access = array:3 [
0 => "1"
1 => "3"
2 => "48"
]
What I am trying to do is to search if any of $id_access
values is present in the database column, template_ids
.
I tried:
Post::where('accessable_to',1)->whereIn('template_ids', $template_access_array)->paginate(3);
Also, I tried:
Post::where('accessable_to',1)->whereRaw("JSON_CONTAINS(template_ids, ".$template_access.")")->paginate(3);
Already viewed this, but it's not working for me.
What about to say:
To see if the
template_ids
JSON field contains "any" of the values in a needle array, you gonna need to utilize multipleOR
'dJSON_CONTAINS
conditions which requires MySQL 5.7:Laravel's query builder will produce a query like:
Which targets records that have any of those IDs in their
template_ids
JSON-typed field.You might be interested in reading a related Laravel internals proposal.