简体   繁体   中英

Laravel 5 raw select query doesn't return anything

I am trying to retrieve data from a database and i need to run the sql as a raw query, this is how I do it:

$var = Nuti::select(DB::raw("select name, image, info from nuti
  where name like '%:search_term%'"), array("search_term" => $term));

return $var;

$var returns an empty array but when I try to run the same query directly in a mysql console, it returns two records.

[EDIT]

I just shortened the query when i posted this question, the need for a raw query is to do something more like this:

$var = Nuti::select(DB::raw("select name, image, info from nuti
  where name like '%:search_term%'") or info %like% '%:search_term%', array("search_term" => $term));

return $var;

You can do it in the following ways.

$data = Nuti::select(['name', 'image', 'info'])->where('name', 'like', "%{$term}%")->get();

$data = Nuti::selectRaw('name, image, info')->where('name', 'like', "%{$term}%")->get();

$data = DB::table('users')->select(['name', 'image', 'info'])->where('name', 'like', "%{$term}%")->get();

$data = DB::table('users')->selectRaw('name, image, info')->where('name', 'like', "%{$term}%")->get();

$data = DB::select("select name, image, info from nuti where name like '%{$term}%'");

You might just need to add ->get();

$var = Nuti::select(DB::raw("select name, image, info from nuti
      where name like '%:search_term%'"), array("search_term" => $term))->get();

You can debug with:

$var = Nuti::select(DB::raw("select name, image, info from nuti
  where name like '%:search_term%'"), array("search_term" => $term))->toSql(); 
dd($var);

edit: What about this?

$var = Nuti::select(DB::raw("select name, image, info from nuti
      where name like '%:".$term."%'"))->get();

If your query is too complex for the query builder and you want to get an collection of models from a raw query, you can use hydrateRaw() :

$var = Nuti::hydrateRaw(
    "select name, image, info from nuti where name like :search_term",
    array("search_term" => "%{$term}%")
);
$var = Nuti::select(['name', 'image', 'info'])->where('name', 'like', "%{$term}%")->get();
return $var;

I think this is all you need.

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