我在这里做的事情可能很愚蠢,但我是laravel的新手,我正在使用查询为数据库应用搜索过滤器。查询正在使用javascript构建并被传递给laravel函数。例如
window.open("/filterResults?types="+types);
//types contains a string like "international#global#europe# etc
现在在Controller中,我将获取字符串types
并将其展开以生成如下查询
$tquery = "Where('type',".$typesArray[0].")";
for($offset=1; $offset < count($typesArray); $offset++) {
$tquery .= "->orWhere('type', ".$typesArray[$offset].")";
}
和执行这样的查询
$firms = Firm::$tquery->get();
显示错误
Access to undeclared static property: App'Firm::$tquery
我怎样才能做我想做的。
p。类型是复选框,其中一些可以被选中或全部选中。
最好使用whereIn()
方法:
$firms = Firm::whereIn('type', $typesArray)->get();
但是如果你需要用你的方式,你可以这样做:
$firm = new App'Firm;
foreach ($typesArray as $type) {
$firm = $firm->orWhere('type', $type);
}
$firms = $firm->get();
您考虑过查询生成器吗?
$firmsQuery = (new Firm)->newQuery();
if($request->has('types')) {
$typesArray = $request->input('types');
foreach ($typesArray as $type) {
$firmsQuery->where(function($query) use ($type) {
$query->orWhere('type', $type);
});
}
}
$firms = $firmsQuery->get();
实际上你使用了糟糕的样式,但是你可以看看DB Raw Expressions