whereJson包含Laravel 5.6无法正常工作?

时间:2018-07-26 18:45:18

标签: php mysql json eloquent laravel-5.6

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

上面雄辩的查询似乎仅在'players'json数组中只有一个项目时才起作用。

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

难道whereJsonContains仅在数据库中看到[1]时有效,而在看到["1","2"]时无效吗?

我对Laravel来说还很陌生,并且一直在努力挣扎。

3 个答案:

答案 0 :(得分:5)

数据类型必须匹配:

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

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

答案 1 :(得分:0)

文档挺简单

  

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

答案 2 :(得分:0)

你可以用orWhere来解决问题

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