Eloquent whereRaw is not working with bindings

旧城冷巷雨未停 提交于 2020-02-04 13:48:10

问题


I have a json column in my database with french characters. So when I use:

App\Job::where('name->fr', 'like', '%Fune%')->count();

It is not finding results for jobs that has an accent in the name like Funéraire. I can accomplish what I want by adding a collate in the query using the whereRaw:

App\Job::whereRaw('json_unquote(json_extract(`name`, \'$."fr"\')) LIKE \'%Fune%\' collate utf8mb4_general_ci')->count();

However, when I use bindings in my whereRaw method:

App\Job::whereRaw('json_unquote(json_extract(`name`, \'$."fr"\')) LIKE ? collate utf8mb4_general_ci', ['%Fune%'])->count();

I am receiving a database error:

COLLATION 'utf8mb4_general_ci' is not valid for CHARACTER SET 'binary' (SQL: select count(*) from jobs where json_unquote(json_extract(name, '$."fr"')) LIKE %Fune% collate utf8mb4_general_ci)

Just wondering why it's not working when I'm passing it with bindings.


回答1:


You need to convert the binding to UTF-8:

App\Job::whereRaw(
    'json_unquote(json_extract(name, \'$."fr"\')) LIKE convert(? using utf8mb4)', 
    ['%Fune%']
)



回答2:


Chin.

if you have a JSON column the DB, you can directly fire a like query on the column as JSON is a string and like %text% search the text in the string.

you don't have to go through this much trouble for finding the alike name.

your query may somewhat look like this,

App\Job::where('name_of_column_of_json', 'like', '%Fune%')->count();

and you will get the desired output.

hit it and let us know, It works or not.



来源:https://stackoverflow.com/questions/58325280/eloquent-whereraw-is-not-working-with-bindings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!