使用“?|”执行查询操作员

Execute query with "?|" operator

我有 table my_tablejsonbsentiments。我需要从此列中删除所有键“10216”和“10191”。

我尝试在 Laravel 中做下一步:

DB::table('my_table')
    ->whereRaw("sentiments ?| ARRAY['10216', '10191']")
    ->update([
        'sentiments' => DB::raw("sentiments - '10216' - '10191'")
    ]);

但是我有下一个错误:

[Illuminate\Database\QueryException]                                                                                 
  SQLSTATE[42601]: Syntax error: 7 ОШИБКА:  ошибка синтаксиса (примерное положение: "")                              
  LINE 1: ...= sentiments - '10216' - '10191' where sentiments | ARRAY[...                                           
                                                               ^ (SQL: update "my_table" 
    set "sentiments" = sentiments - '10216' - '10191' 
    where sentiments ?| ARRAY['10216', '10191'])

因为我看到“?”看起来像参数。如何转义这个符号?

更新

我也试着写了两个问题:sentiments ??| ARRAY:

[Illuminate\Database\QueryException]                                                                                 
  SQLSTATE[42883]: Undefined function: 7 ОШИБКА:  оператор не существует: jsonb ??| text[]                             
  LINE 1: ...= sentiments - '10216' - '10191' where sentiments ??| ARRAY[...                                           
                                                               ^                                                       
  HINT:  Оператор с данными именем и типами аргументов не найден. Возможно, вам следует добавить явные приведения тип  
  ов. (SQL: update "my_table" set "sentiments" = sentiments - '10216' - '10191' where sentiments ??|  
   ARRAY['10216', '10191']) 

感谢@degr!它适用于未记录的函数 jsonb_exists_any():

DB::table('my_table')
    ->whereRaw("jsonb_exists_any(sentiments, ARRAY['10216', '10191'])")
    ->update([
        'sentiments' => DB::raw("sentiments - '10216' - '10191'")
    ]);

更新

与使用运算符 ?|.

不同,此方法不使用 jsonb 字段上的索引

亲爱的朋友你可以使用

CREATE OPERATOR ~@& (LEFTARG = jsonb, RIGHTARG = text[], PROCEDURE = jsonb_exists_any)

然后像这样写你的查询

DB::table('my_table')
->whereRaw("sentiments ~@& ARRAY['10216', '10191']")
->update([
    'sentiments' => DB::raw("sentiments - '10216' - '10191'")
]);