简体   繁体   中英

whereJsonContains Laravel 5.6 not working?

$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.

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.

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

You can solve the problem with orWhere

$id = "1" // or = 1
Model::whereJsonContains('ids', [$id])
  ->orWhere(function (Builder $q) use ($model) {
    $q->whereJsonContains('ids', [(string)$id]);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM