2

I'm trying to query a MySQL database table which contains a JSON column.

In MySQL the following query runs

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

And I'm able to see the result from mysql console.

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

However, when I use a Laravel QueryBuilder to build this query. It throws grammar error.

The Laravel code (inside a controller):

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

The error message:

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)

Could you please help me know where am I doing wrong?

8
  • Try this: DB::raw('CAST('.$memberList.' AS JSON') Commented Mar 26, 2016 at 22:16
  • Have tried that, no luck.. Commented Mar 26, 2016 at 22:17
  • Can you do this, dd($memberList) to check the value of $memberList Commented Mar 26, 2016 at 22:21
  • @geckob well, I think you can see from the error output. It is just[1,2,3] Commented Mar 26, 2016 at 22:25
  • @aldrin27 yes, I put in {'members':[1,2,3]}; in the get request. Commented Mar 26, 2016 at 22:34

1 Answer 1

3

Firstly you must convert $memberlist to string.

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

Then you can use;

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

I'm sure it will work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.