mysql - 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”中,响应返回来自表单输入的两个日期。我的挑战是将这些日期链接到查询变量中。我怎么做?谢谢。
解决方案
对变量使用绑定
$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]));
推荐阅读
- android - 使用动态屏幕时如何防止内存泄漏?
- bash - 在终端中运行 matlab 命令
- grep - 为什么 xargs 的退出代码会因“-I”选项的存在而不同?
- reactjs - 具有解构变量的 React SetState 提供了错误的结果
- angular - 在自定义 Angular 库中添加外部库(Bootstrap、jquery ..)的脚本
- pipenv - 如何使用 HTTPS 和 SSH URL 指定 VCS 依赖项
- python - InvalidArgumentError:您必须使用 dtype float 和 shape 为占位符张量“Placeholder”提供一个值
- c++ - 如何在 r-tree 的内部节点存储一些信息?
- sql - Bill(Master) 和 BillDetail(Detail) 表:使用表连接生成查询
- html - 如何在标签/Div 之后删除多余的空间