問題描述
我在查詢 json 列時(shí)遇到問題.
I am having trouble querying a json column.
以前我的代碼是
$query->whereIn('user', $users);
現(xiàn)在我已將 db 類型更改為 JSON 列,并且正在嘗試修改新版本的代碼.
Now i have changed the db type to JSON column and am trying to modify the code for the new version.
在 RAW MYSQL 中這是有效的
In RAW MYSQL this works
JSON_CONTAINS(user, '"tom","Bill"')
但是當(dāng)我把它放在 eloquent/php 中時(shí),它一直失敗或返回注釋.在這里,我傳入了一組用戶,之前使用的是在原始 SQL 中工作的 WhereIn
But when i put it in eloquent / php it keeps failing or returning noting. Here i am passing in an array of Users, previous using an WhereIn which works in raw SQL
$leads->whereRaw("JSON_CONTAINS(user, '"$users"')")
任何想法如何使它在 Laravel 中工作,以便我可以傳入一個(gè)字符串?dāng)?shù)組,并針對包含一個(gè)字符串?dāng)?shù)組的 json 列查詢它們.
Any idea how to make it work in Laravel so i can pass in an array of strings, query them against the json column which contains an array of strings too.
我的 Json 列有這樣的數(shù)據(jù)
My Json colum has data like so
["Paul", "Tom", "Bob"]
推薦答案
MySQL 需要一個(gè) JSON 字符串:
MySQL expects a JSON string:
$leads->whereRaw('JSON_CONTAINS(user, ?)', [json_encode($users)])
在 Laravel 5.6.24 中你可以使用 whereJsonContains()
:
In Laravel 5.6.24 you can use whereJsonContains()
:
$leads->whereJsonContains('user', $users)
這篇關(guān)于Laravel Eloquent 使用 Where In? 查詢 JSON 列的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!