0

I have the following record in my database where I have to get all records containing any of the records.

Table record contains: $record_ids = ["123","234","111"]

Trying to search for it like the following with Laravel:

$records = DB::table('records_table')
  ->where('id', $id)
  ->whereRaw('JSON_CONTAINS(record_id, ?)', $record_ids)
  ->pluck('records');

I've also tried with similar solutions like:

->whereIn('record_id', $record_ids)

I'm using Laravel 5.5 and Mysql.

Update: It works when I 'manually' add it like the following:

->whereIn('record_id', ["123","234","111"])

But when fetching the array from the database it doesn't work

8
  • What type of column is record_id? Commented Sep 28, 2018 at 19:54
  • It's a JSON table (Have tried changing to text also). Commented Sep 28, 2018 at 19:58
  • Are the values in the JSON array integers or strings? Commented Sep 28, 2018 at 20:00
  • Wait sorry, my mistake! The record_id is a integer array Commented Sep 28, 2018 at 20:04
  • You want to find the rows where the record_id column contains all the ids from $record_ids? Commented Sep 28, 2018 at 20:09

2 Answers 2

1

I think you want to use here:

->whereIn('record_id', json_decode($json, true));
Sign up to request clarification or add additional context in comments.

1 Comment

Yes! That worked! I tried something similar and the issue was in the code above so the result didn't return anything.
1

The types have to match (integer vs. string) and the search value has to be JSON encoded:

$search = json_encode(array_map('intval', $record_ids));

$records = DB::table('records_table')
    ->where('id', $id)
    ->whereRaw('JSON_CONTAINS(record_id, ?)', $search)
    ->pluck('records');

In Laravel 5.6, you can use whereJsonContains():

->whereJsonContains('record_id', array_map('intval', $record_ids));

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.