简体   繁体   English

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

The eloquent query above seems to only work when there is a single item in the 'players' json array.上面的 eloquent 查询似乎只在 'players' json 数组中有单个项目时才有效。

The data stored in the database looks as follows: [1] vs ["1","2"]数据库中存储的数据如下所示: [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"] ? whereJsonContains 仅在数据库中看到[1]而不是在看到["1","2"]时才起作用,是否有原因?

I am pretty new to Laravel and have been struggling with this one a bit.我对 Laravel 很陌生,并且一直在努力解决这个问题。

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 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根据您在该 json 列中的内容(如果 id),将players替换为players players->id

You can solve the problem with orWhere你可以用 orWhere 来解决这个问题

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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