简体   繁体   English

Laravel 5 Raw Select查询不返回任何内容

[英]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: 我正在尝试从数据库检索数据,我需要将sql作为原始查询运行,这是我的方法:

$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. $ var返回一个空数组,但是当我尝试直接在mysql控制台中运行同一查询时,它返回两条记录。

[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(); 您可能只需要添加-> 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() : 如果您的查询对于查询生成器而言过于复杂,并且您希望从原始查询中获取模型集合,则可以使用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. 我认为这就是您所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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