Making a Laravel 5.4 query on a JSON field containing a JSON array

后端 未结 1 832
栀梦
栀梦 2020-12-11 06:48

i\'m trying to query a JSON field containing an array of values. For exemple sake we\'ll name the table \"User\" and the field \"Friends\".

相关标签:
1条回答
  • 2020-12-11 07:31

    Your whereRaw attempt is very close. If you were storing a single object, your path would be $.id. However, since you're storing an array of objects, your path is $[*].id. This should work for you:

    User::whereRaw('JSON_CONTAINS(friends->"$[*].id", "3")')->get();
    

    The friends->"$[*].id" selector (which is just a shortcut for JSON_EXTRACT()) will return a json array of the ids. JSON_CONTAINS() will then check if that json array contains the specified id.

    Another option would be to build a json search string to use for JSON_CONTAINS(). For example, this query should also work:

    User::whereRaw('JSON_CONTAINS(friends, \'{"id": 3}\')')->get();
    

    This avoids the first call to JSON_EXTRACT(), so you're only calling one json method. I do not know which version would actually be faster, or if there would be any difference.

    Also, on a side note related to JSON_SEARCH(), this function will only work if you are searching for string values. Since your json shows that the ids are represented as integers instead of strings, JSON_SEARCH() will not work. MySQL claims this is intended behavior (bug 79233 and dup bug 79316).

    Just for reference, here is the documentation for the json search methods.

    0 讨论(0)
提交回复
热议问题