php - 使用 "?|"运算符执行查询

标签 php postgresql laravel pdo laravel-5.3

我有表 my_tablejsonb情感。我需要从此列中删除所有键“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 ??|数组:

[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 字段上的索引。

关于php - 使用 "?|"运算符执行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41333057/

相关文章:

php - 由于 INT 值而调用 boolean 的成员函数 fetch()?

php - 代码点火器错误 "Unable to connect to your database server using the provided settings"

sql - "$$ 处或附近未终止的美元引号字符串

php - 如何在 PHP 中调试 "array_key_exists() expects parameter 2 to be array, integer given"?

php - Laravel,将数据从数组保存到数据库

php - 如何将这个字符串分解成这样的数组?

javascript - 如何在更改下拉列表中存储与数字(值)对应的文本?

sql - 按组限制结果集

mysql - 如何选择SQL数据库表中的第n行?

validation - Laravel 5 FormRequest 数组输入的自定义消息