问题
$rosters = EventRosters::where('event_id', $event_id)
->whereJsonContains('players', $user_id)
->whereNull('deleted_at')
->get();
The eloquent query above seems to only work when there is a single item in the 'players' json array.
The data stored in the database looks as follows:
[1]
vs ["1","2"]
Is there a reason the whereJsonContains is only working when it sees [1]
in the db but not when it sees ["1","2"]
?
I am pretty new to Laravel and have been struggling with this one a bit.
回答1:
The data types have to match:
// [1, 2]
->whereJsonContains('players', 1) // Works.
->whereJsonContains('players', '1') // Doesn't work.
// ["1", "2"]
->whereJsonContains('players', '1') // Works.
->whereJsonContains('players', 1) // Doesn't work.
回答2:
The documentation is kinda straight forward
https://laravel.com/docs/5.6/queries#json-where-clauses
$rosters = EventRosters::where('event_id', $event_id)
->whereJsonContains(['players', [1,2]])
//->whereNull('deleted_at') Unless you setup a scope at the model's bootup,
//Eloquent won't fetch soft deleted records
->get();
Depending on what you've got in that json column (if id), replace players
with players->id
来源:https://stackoverflow.com/questions/51545655/wherejsoncontains-laravel-5-6-not-working