我正在尝试对表中的列之一使用substr。但是,它返回此错误:Method Illuminate\Support\Collection::raw does not exist.
我的控制器在这里:
public function search(Request $request)
{
$q = $request->q;
if ($q !== null && trim($q) !== ""){//here
$estates = \DB::table('estates')
->where("name","LIKE", "%" . $q . "%")
->orWhere("address","LIKE", "%" . $q . "%")
->orWhere("company_name","LIKE", "%" . $q . "%")
->orderBy('price')->get()
->raw(substr('address', 1, 4))->get();
if(count($estates) > 0){
return view("search", compact('estates'))->withQuery($q);
}
}
$estates = array();
return view("search", compact('estates'))->withMessage("No Found!");
}
我认为这行不是很有效吗? raw(substr('address', 1, 4))->get();
有解决这个问题的主意吗?
谢谢!
答案 0 :(得分:1)
您不能将->raw()
用作函数,因为它根本不存在。根据您的查询,您想从select
Address
的Substr。在这种情况下,您将使用以下内容:
$estates = \DB::table('estates')
->where("name","LIKE", "%" . $q . "%")
->orWhere("address","LIKE", "%" . $q . "%")
->orWhere("company_name","LIKE", "%" . $q . "%")
->orderBy('price')->get()
->select(
'states.*',
\DB::raw('SUBSTR(`address`, 1, 4) as short_address')
)->get();
并像这样访问它:
$estates->first()->short_address
答案 1 :(得分:0)
使用DB :: raw()
$estates = \DB::table('estates')
->where("name","LIKE", "%" . $q . "%")
->orWhere("address","LIKE", "%" . $q . "%")
->orWhere("company_name","LIKE", "%" . $q . "%")
->orderBy('price')
->select(\DB::raw("SUBSTR('address', 1, 4))")->get();