简体   繁体   中英

Laravel Eloquent: Query returns no records but SQL does

I have this query:

$query = City::query();

    $query->select('id', 'name as default_name', 'translations->' . $request["lang"] . ' as name', 'country_id');

    $query->where(function ($query) use ($request) {
        $query->whereRaw('LOWER(translations->"$.' . $request["lang"] . '") like ?', "'%" . strtolower($request['search']) . "%'");
        $query->orWhere('name', 'like', "'%" . strtolower($request->search) . "%'");
    });

    if ($request->country !== null) {
        $query->whereRaw('country_id = '. $country);
    }

    $results = $query->get();

That translates to this SQL:

select `id`, `name` as `default_name`, json_unquote(json_extract(`translations`, '$."en"')) as `name`, `country_id` 
from `cities` 
where (LOWER(translations->"$.en") like '%barcelona%' or `name` like '%barcelona%') 
and country_id = 207

Eloquent is not returning any records while SQL does:

在此处输入图像描述

Any clue on whats wrong here?

Thanks!

Is Ok the part?

if ($request->country !== null) {
    $query->whereRaw('country_id = '. $country);
}

Its seems like

 if ($request->country !== null) {
     $query->where('country_id', $request->country);
 }

And in the select part the JSON column not has $ operator.

This line in the code seemed to be the problem:

$query->orWhere('name', 'like', "'%" . strtolower($request->search) . "%'");

I found a solution using orWhereRaw() :

$query->orWhereRaw('LOWER(`name`) LIKE ? ','%'. trim(strtolower($request['search'])) .'%')

This line converts column "name" data to lowercase and trims and lowers the search parameter.

I hope it help others in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM