$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来说还很陌生,并且一直在努力挣扎。
答案 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)
文档挺简单
$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]);
});