问题
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