【问题标题】:Laravel query variable as stringLaravel 查询变量作为字符串
【发布时间】:2016-10-22 07:54:17
【问题描述】:

我在这里做的可能很愚蠢,但我是 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

我怎样才能做我想做的事。

PS。类型是复选框,其中一些可以选中或全部选中。

【问题讨论】:

    标签: php mysql laravel laravel-5 eloquent


    【解决方案1】:

    最好使用whereIn()方法:

    $firms = Firm::whereIn('type', $typesArray)->get();
    

    但如果你需要使用你的方式,你可以这样做:

    $firm = new App\Firm;
    
    foreach ($typesArray as $type) {
        $firm = $firm->orWhere('type', $type);
    }
    
    $firms = $firm->get();
    

    【讨论】:

    • 真棒whereIn Rocks,:) 谢谢伙计。
    【解决方案2】:

    您考虑过查询生成器吗?

    $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();
    

    【讨论】:

    • 非静态方法 Illuminate\Database\Eloquent\Model::newQuery() 不应被静态调用,假设 $this 来自不兼容的上下文
    • 哎呀!请检查更新的答案。有一个无意的错误。应该是$firmsQuery = (new Firm)-&gt;newQuery();
    • 感谢您的关注和时间,但现在错误是Undefined variable: type
    • 已修复。它应该是foreach 中的$typesArrayforeach ($typesArray as $type)
    【解决方案3】:

    其实你的风格不好,你可以看看DB Raw Expressions

    【讨论】:

      猜你喜欢
      • 2018-06-13
      • 2011-04-19
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 2014-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多