【问题标题】:Execute query with "?|" operator使用“?|”执行查询操作员
【发布时间】:2017-05-11 00:36:39
【问题描述】:

我有表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 ОШИБКА:  ошибка синтаксиса (примерное положение: "$1")                              
  LINE 1: ...= sentiments - '10216' - '10191' where sentiments $1| 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:感谢您的想法,但它没有帮助。我已经更新了答案。
  • @degr:谢谢!它有效:jsonb_exists_any(sentiments, array['10216', '10191'])。请发布答案,我会接受。
  • 这不是我的答案,你自己做的

标签: php postgresql laravel pdo laravel-5.3


【解决方案1】:

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

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

更新

与使用运算符 ?| 不同,不使用 jsonb 字段上的索引。

【讨论】:

  • 未定义函数:7 错误:函数 jsonb_exists_any(json, text[]) 不存在,postgres 10
  • @LevonBabayan 尝试将第一个参数转换为jsonb
【解决方案2】:

亲爱的朋友你可以使用

创建操作员 ~@& (LEFTARG = jsonb, RIGHTARG = text[], PROCEDURE = jsonb_exists_any)

然后像这样写你的查询

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

【讨论】:

    猜你喜欢
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2020-05-30
    • 1970-01-01
    相关资源
    最近更新 更多