首页 > 解决方案 > MySql 原始查询中的变量

问题描述

我有这个生成 CSV 的原始查询,它以“硬编码模式”返回 2 个日期我想用变量替换这些值我该怎么办?在这种情况下,它将是由“post”注入的变量,其中 Axios 来自 React.js 的组件。查询运行成功,反应组件也运行良好。

Laravel(5.8 版)文件:

//...rest of the code omitted

$api->get('orders1/csv1', function () {      
    
   $sql= DB::select(DB::raw(    
    "
   SELECT orders.id,

//... rest of the query ommited      
// this 2 dates above are needed to be replaced by variables      
      WHERE tr.tenant_relations_type = 'App\\Models\\Order'
      AND orders.created_at BETWEEN '2021-01-01 00:00:00' and '2021-06-07 00:00:00' AND 
//... rest of the query ommited      
   
   "));    
    return (new Response(json_encode($sql), 200))->header('Content-Type', 'text/csv' );    
});
//... rest of the code omitted

ReactJS 文件:

//...省略其余代码

const saveCsv = (data, cb) => {
    axios
      .post(`${process.env.REACT_APP_API_EASYMUNDI_URL}/api/orders1/csv1`, data, {
        headers: { Authorization: AuthStr }
      })
      .then(function(response) {
        cb(response);
        console.log('response: ')
        console.log(response)
      })
      .catch(function(error) {
        console.log(error);
        cb({
          error: true,
          message: error.message,
          status: error.response && error.response.status ? error.response.status : ''
        });
      });
  };

  // .. rest of the code omitted

正如我之前所说,这个组件运行成功。在“console.log”中,响应返回来自表单输入的两个日期。我的挑战是将这些日期链接到查询变量中。我怎么做?谢谢。

标签: mysqlreactjslaravel

解决方案


对变量使用绑定

$startDate = '2021-01-01 00:00:00';
$endDate = '2021-06-07 00:00:00';
$sql= DB::select(DB::raw(    
    "
   SELECT orders.id,

//... rest of the query ommited          
      WHERE tr.tenant_relations_type = ?
      AND orders.created_at BETWEEN ? and ? AND 
//... rest of the query ommited      
   
   ", [Order::class, $startDate, $endDate]));//place your variables in order here

如果您不想跟踪绑定的顺序,可以使用关联数组。

$sql= DB::select(DB::raw(    
    "
   SELECT orders.id,

//... rest of the query ommited          
      WHERE tr.tenant_relations_type = :model
      AND orders.created_at BETWEEN :start and :end AND 
//... rest of the query ommited      
   
   "; ['start' => $startDate, 'end' => $endDate, 'model' => Order::class]));    

推荐阅读