【发布时间】:2020-01-24 12:55:16
【问题描述】:
我对 Laravel 查询生成器有疑问。当我尝试将包含某种 sql 代码的变量绑定到我的绑定参数时,它不返回任何结果。如果我运行 enableQueryLog() 我可以看到查询和绑定是正确的。所以代码提供了一个完美的查询,但它并没有相应地执行。
我已经尝试打印出所有重要的变量。我启用了查询日志以查看是否所有设置都正确,它是正确的。当我将变量放入 whereRaw() 中时,就像没有绑定一样,它工作正常。只是没有绑定。
这是我运行的代码:
public function getCarbrands() {
$name = 'name != Ford';
try {
$brands = DB::table('ni_carbrands')
->whereRaw(':name',['name'=>$name])
->select('id','name')
->get();
echo json_encode( array('info' => 1 ,'status' => 'Successfully found car brands', 'details' => $brands));
} catch(Exception $e){
echo json_encode( array('info' => 0 ,'status' => 'Error finding car brands', 'e' => $e));
}
}
我知道这种绑定功能的使用是不必要的,它只是对我想要构建的其他一些功能的测试。 这是我的查询日志返回的内容:
array:1 [▼
0 => array:3 [▼
"query" => "select `id`, `name` from `ni_carbrands` where :name"
"bindings" => array:1 [▼
0 => "name != Ford"
]
"time" => 190.25
]
]
查询的组成部分似乎都正确,但生成它似乎有些麻烦。
预期的结果是这样的:
{
"info": 1,
"status": "Successfully found car brands",
"details": [
{
"id": 1,
"name": "Toyota"
},
{
"id": 2,
"name": "Fiat"
},
{
"id": 3,
"name": "Iveco"
},
{
"id": 4,
"name": "Citroën"
},
{
"id": 5,
"name": "Opel"
},
{
"id": 6,
"name": "Mercedes"
},
{
"id": 8,
"name": "Volkswagen"
},
{
"id": 9,
"name": "Renault"
},
{
"id": 10,
"name": "MAN"
},
{
"id": 11,
"name": "Nissan"
},
{
"id": 12,
"name": "Hyundai"
},
{
"id": 13,
"name": "Peugeot"
}
]
}
但实际结果是:
{"info":1,"status":"Successfully found car brands","details":[]}
非常感谢您的帮助。
【问题讨论】:
-
能否给出响应码??您在哪里将此数据添加到详细信息??
-
对不起,我现在把整个函数都放了。响应码是底部提供的信息。
标签: laravel laravel-query-builder