Reputation: 187
My DB column field ("colors") contains an array structured like this:
["1","2","3"]
My current query look like this, simplified for better example:
$value = '1';
$cards = Card::query()
->where('colors', 'like', '%' . $value . '%')
->get();
The problem is, it fetches data from other columns, for example ["5","8","13"]
will match "13"
instead of the strict $value
, which should be "1"
.
How do I write this query the correct way?
Upvotes: 4
Views: 11513
Reputation: 904
I had a multilingual Slug. I got it with this code
$category = CategoryModel::query()->whereJsonContains('slug->' . app()->getLocale(), $category)->first();
dd($category->toArray());
Upvotes: 0
Reputation: 4365
You can match it along with the quotes
$cards = Card::query()
->where('colors', 'like', '%"' . $value . '"%')
->get();
Upvotes: 2
Reputation: 15105
used whereJsonContains Method here
value like this then do like that ["1","2","3"]
$cards = Card::query()
->whereJsonContains('colors', '1')
->get();
if value like that [1,2,3] then used like that
$cards = Card::query()
->whereJsonContains('colors', 1)
->get();
Upvotes: 5
Reputation: 2932
You can query the JSON array fields as follows
$cards = Card::query()
->whereNotNull("colors->$value")
->get();
The above query will return cards having colour in the $value
Upvotes: 0