简体   繁体   中英

how to use raw sql with laravel eloquent builder

I need to get name and id from my user table, name is in two column as first_name and last_name . This is what I have done

$user = User::select('id',DB::raw("CONCAT(`first_name`, ' ' ,`last_name`) AS name"))
        ->where('name', 'like' ,$token)

which gives me an error Unknown column 'name' in 'where clause' . I printed out the raw sql which looks like this

select `id`, CONCAT(`first_name`, ' ' ,`last_name`) AS name from `user` where `name` like ? and `user`.`deleted_at` is null

How can I use concat and like with my eloquent builder properly?

Try This:

$user = User::select('id',DB::raw("CONCAT(`first_name`, ' ' ,`last_name`) AS name"))
        ->where(DB::raw("CONCAT(`first_name`, ' ', `last_name`)"), 'LIKE', "%".$token."%");

try to use like that

$user = User::select('id',DB::raw("CONCAT(first_name, ' ' ,last_name) as name"))
        ->where(DB::raw("CONCAT(first_name, ' ' ,last_name)"), 'like' ,"%".$token."%")

You should try this:

$user = User::select('Tenant_Id', DB::raw('CONCAT(first_name, " ", last_name) AS name'))
        ->where('name', 'like' ,$token)

Try this-

$user = User::select('id',DB::raw("CONCAT(`first_name`, ' ' ,`last_name`) AS name"))
    ->where(DB::raw("CONCAT(`first_name`,' ', `last_name`)"), 'LIKE', "%" . $name . "%");

It worked for me.

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