【问题标题】:How can I solve case-sensitive where like statement on json data in Laravel eloquent?如何解决 Laravel eloquent 中关于 json 数据的区分大小写的 where like 语句?
【发布时间】:2018-09-15 23:15:48
【问题描述】:

我使用 Laravel 5.6 和 mysql 数据库。

我的 Laravel eloquent 查询是这样的:

Order::where('information->owner', 'like', '%'.$receipt.'%')->paginate(5);

信息字段是 JSON 类型。

{"owner": "Chelsea"}

如果$receiptChel,则查询返回结果。

但如果$receiptchelCHEL,则结果为空

我该如何解决这个问题?

【问题讨论】:

标签: mysql laravel laravel-5 laravel-eloquent laravel-5.6


【解决方案1】:

如果每个所有者都以大写首字母开头,您可以使用ucfirst 将字符串的首字母大写

$receipt = ucfirst($receipt);
Order::where('information->owner', 'like', '%'.$receipt.'%')->paginate(5);

【讨论】:

  • 它不起作用。看来information->owner也需要改成小写
  • 是的,你说得对,我已经更新了我的答案,所以你可以使用 ucfirst()
  • 好吧,我猜你似乎需要在将其插入数据库之前弄清楚你是数据结构 - 可能有一个所有者名称字段(全部小写)+所有者名称标签并且只匹配在所有者名称字段上
  • 看来我不会用这种方式。我尝试这种方式:stackoverflow.com/questions/46238718/…。我实施到我的情况。但它不起作用。似乎是因为我的情况是 json.也许你可以帮助我参考
【解决方案2】:

转换为小写或大写后尝试比较值。

Order::whereRaw('LOWER(JSON_EXTRACT(information, "$.owner")) like ?', ['"%' . strtolower($receipt) . '%"'])
     ->paginate(5);

【讨论】:

  • 存在错误:SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'information->owner) like %?%' at line 1 (SQL: select count(*) as aggregate from orders where LOWER(information->owner) like %chel%)"
  • like %?%更改为like "%?%"
  • 仍然存在错误。像这样的错误:SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'information->owner) like "%?%"' at line 1 (SQL: select count(*) as aggregate from orders where LOWER(information->owner) like "%chel%")
  • 这个好像不行,因为字段信息是json数据
  • 更新了答案。立即尝试
猜你喜欢
  • 2014-10-19
  • 2016-09-03
  • 2016-05-19
  • 1970-01-01
  • 2020-12-06
  • 2021-02-27
  • 2017-01-23
  • 1970-01-01
  • 2018-11-05
相关资源
最近更新 更多