【问题标题】:Laravel query MySQL JSON column using equal operatorLaravel 使用相等运算符查询 MySQL JSON 列
【发布时间】:2016-07-14 11:06:15
【问题描述】:

我正在尝试查询包含 JSON 列的 MySQL 数据库表。

在 MySQL 中运行以下查询

mysql> select members from `conversations` where `members` = CAST('[1,2,3]' AS JSON) limit 3;

我可以从 mysql 控制台看到结果。

+-----------+
| members   |
+-----------+
| [1, 2, 3] |
| [1, 2, 3] |
| [1, 2, 3] |
+-----------+

但是,当我使用 Laravel QueryBuilder 构建此查询时。它会引发语法错误。

Laravel 代码(在控制器内):

$memberList = $request->input('members');
DB::table("conversations")->where('members', '=', DB::raw('CAST(\''.$memberList.'\'AS JSON'))->get();

错误信息:

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 '' at line 1 (SQL: select * from `conversations` where `members` = CAST('[1,2,3]'AS JSON)

你能帮我看看我哪里做错了吗?

【问题讨论】:

  • 试试这个:DB::raw('CAST('.$memberList.' AS JSON')
  • 试过了,没有运气..
  • 你可以这样做吗,dd($memberList) 来检查 $memberList 的值
  • @geckob 好吧,我想你可以从错误输出中看到。它只是[1,2,3]
  • @aldrin27 是的,我输入了 {'members':[1,2,3]};在获取请求中。

标签: php mysql json laravel


【解决方案1】:

首先您必须将$memberlist 转换为字符串。

$memberList = $request->input('members');
$memberListString = '[' . implode(",", $memberlist) . ']';

然后就可以使用了;

DB::table("conversations")
    ->whereRaw("members = CAST('".$memberListString."' AS JSON)")->get();

我相信它会起作用的。

【讨论】:

    猜你喜欢
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    相关资源
    最近更新 更多