whereJsonContains Laravel 5.6 不工作?

whereJsonContains Laravel 5.6 not working?

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

上面的 eloquent 查询似乎只在 'players' json 数组中只有一个项目时有效。

数据库中存储的数据如下所示: [1] 对比 ["1","2"]

whereJsonContains 仅在数据库中看到 [1] 时才起作用,而在看到 ["1","2"] 时不起作用,这是有原因的吗?

我是 Laravel 的新手,一直在努力解决这个问题。

文档比较简单

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();

根据您在 json 列中的内容(如果 id),将 players 替换为 players->id

数据类型必须匹配:

// [1, 2]
->whereJsonContains('players', 1)   // Works.
->whereJsonContains('players', '1') // Doesn't work.

// ["1", "2"]
->whereJsonContains('players', '1') // Works.
->whereJsonContains('players', 1)   // Doesn't work.

您可以使用 orWhere

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