首页 > 解决方案 > laravel 在查询中显示请求值无

问题描述

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

我的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
  ]
]

标签: phpajaxlaravel

解决方案


您看到问号是因为 laravel 使用参数绑定

选择 * 从products哪里price= ?

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

无论如何:如果您想使用其参数进行 sql 查询,您可以使用此函数

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;
    }

推荐阅读