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

解决方法

您会看到问号,因为laravel使用parameters binding

products中选择*,其中price =吗?

当查询在数据库上执行时,将从products中选择*,其中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;
    }
,

这对于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;
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...