【问题标题】:laravel show request value none in querylaravel 在查询中显示请求值无
【发布时间】:2021-01-10 12:35:37
【问题描述】:

我想使用价格过滤一些数据,但是当我们回显请求值时它给出正确但是当我把它放在查询中时它显示“?”

我的 ajax 调用

<script>
        $(document).ready(function() {
            $("#price_filter").on("change", function() {
                var price = this .value;
                var _token = $('input[name="_token"]').val();
                $.ajax({
                    url:"{{ route('indexController.pricefilter') }}",
                    type:"POST",
                    dataType:"json",
                    data:{price,_token},
                    success: function(response){
                        console.log(response);
                        // $("#filterdata").html(response);
                    }
                });
            })
        })  
</script>

我的路线

Route::post('indexController/pricefilter','indexController@pricefilter')->name('indexController.pricefilter');

我的功能

public function pricefilter(Request $request){
    echo $price = $request->get('price');

    return $products = DB::table('products')
        ->where('price','=', $price)
        ->tosql();
}

我的查询结果

400
select * from `products` where `price` = ?

它实际上看起来像

select * from `products` where `price` = 400

这是结果

array:1 [
  0 => array:3 [
    "query" => "select * from `products` where `price` <= ?"
    "bindings" => array:1 [
      0 => "1001"
    ]
    "time" => 3.87
  ]
]

【问题讨论】:

  • 检查输出dd($request-&gt;price);,还是空?
  • 它显示值但查询不使用价格过滤数据它返回所有数据
  • 但是当我们把这个 -&gt;where('price','&lt;', $prod_price) 放到 -&gt;where('price','&lt;', 500) 它工作正常

标签: php ajax laravel


【解决方案1】:

你看到问号是因为 laravel 使用 parameters binding

products 中选择 * 其中price = ?

当在 db 上执行查询时,它将选择 * from products where price = 400

无论如何:如果你想用它的参数来查询你的 sql,你可以使用这个function

public function getEloquentSqlWithBindings($query)
{
    return vsprintf(str_replace('?', '%s', $query->toSql()), collect($query->getBindings())->map(function ($binding) {
        return is_numeric($binding) ? $binding : "'{$binding}'";
    })->toArray());
}

现在:

public function pricefilter(Request $request){
    $query= $products = DB::table('products')
            ->where('price','=', $price);
 echo($this->getEloquentSqlWithBindings($query));
return $query;
    }

【讨论】:

    【解决方案2】:

    这对于 Laravel 来说是正常的。

    要查看您可以使用的真实数据库查询

    DB::enableQueryLog();
    // and then you can get query log
    dd(DB::getQueryLog());
    

    所以你的代码看起来像这样

    public function pricefilter(Request $request){
        echo $price = $request->get('price');
    
        DB::enableQueryLog();
        $products = DB::table('products')
            ->where('price','=', $price)
            ->get();
        dd(DB::getQueryLog());
    
        return $products;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-04
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      相关资源
      最近更新 更多