1

I am trying to access specific data in a json column using a laravel controller, the DB column is called 'figuresinorder'. I want to access the "wants" key but it's not working when there are multiple values stored.

{"wants": ["1"], "trades": ["12,33,234"]} - this works

{"wants": ["1,2,3"], "trades": ["12,33,234"]} - does not work

The query in the controller is as follows:

$figures2 = customtrades::whereJsonContains('figuresinorder->wants', ['1'])->get();

Any help will be greatly received, been stuck on this for longer than I dare to admit.

4
  • 1
    Will be {"wants": ["1","2","3"], "trades": ["12,33,234"]} Commented Oct 12, 2020 at 13:03
  • 1
    insomniac22. Are you sure that searhching for ["1"] would return TRUE if the source is ["1,2,3"]. I would guess it would work if you search for ["1,2,3"]. Commented Oct 12, 2020 at 13:04
  • 1
    ["1,2,3"] is array has one string, your problem is storing data. should be: ["1", "2", "3"] Commented Oct 12, 2020 at 13:09
  • Sta - the data is stored directly by laravel in that format, I have tried using the format you suggested but this does still not return the required data. Toolbox - When the query works is does return the collection correctly rather than a TRUE statement. I need to be able to search directly for the individual number id's rather than the whole array. Commented Oct 12, 2020 at 13:10

1 Answer 1

2

MySQL & PostgreSQL support whereJsonContains() with multiple values like this way :

customtrades::whereJsonContains('figuresinorder->wants', ['1','2','3'])->get();

For more, see the documentation here

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

7 Comments

The OP wants to return any row where wants contains a 1 this doesnt do that
The way I'm storing the data is incorrect as stated in the first comment. When updating the DB column values I get the required response. Surprising as the stored data is the way laravel is storing data from my session. Thanks for your help Sta.
@Wesley according to the official documentation, you need to sort the dara like the above method
@insomniac22 Selecting this as the correct answer is misleading and incorrect. As you stated, the issue was in the way you were storing the data, not in the way you were selecting it
@sta Please add a comment along the lines of "You are storing your data incorrectly as a comma separated string instead of an array. If you change your storing to properly store an array of strings, then your original attempt will work as expected" This would be a correct answer if it included that or something similar.
|

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.