whereJsonContains Laravel 5.6无法正常工作?

whereJsonContains Laravel 5.6无法正常工作?

问题描述:

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

  $ rosters = EventRosters :: where('event_id',$ event_id)
  - > whereJsonContains  ('players',$ user_id)
  - > whereNull('deleted_at')
  - > get(); 
  code>  pre> 
 
 

上面的雄辩查询似乎 只有在'players'json数组中有一个项目时才能工作。 p>

存储在数据库中的数据如下所示: [1] code> vs [“1”,“2”] code> p>

是否存在whereJsonContains仅在看到 [1] code>时才有效的原因 在数据库中,但不是在它看到 [“1”,“2”] code>? p>

我对Laravel很新,并且一直在努力解决这个问题。 位。 p> div>

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