简体   繁体   English

无法在Laravel原始查询中绑定参数

[英]Unable to bind parameters in Laravel raw query

I'm trying to bind vars to my raw query, 我正在尝试将vars绑定到我的原始查询,

$query = "SELECT 1 AS rank, 'CATEGORY' AS type, category_id AS id, name AS name
          FROM category_translations
          JOIN categories ON categories.id = category_translations.category_id
          WHERE name LIKE '%?%'";

$results = DB::select($query, ['ger']);

But I am unable to do so. 但是我做不到。 I have tried by binding named params, and also using DB::raw inside DB::select without any success. 我尝试通过绑定命名的参数,并在DB::select内使用DB::raw进行任何尝试。

What am I doing wrong here? 我在这里做错了什么?

try to used like that 尝试那样使用

$query = "SELECT 1 AS rank, 'CATEGORY' AS type, category_id AS id, name AS name
          FROM category_translations
          JOIN categories ON categories.id = category_translations.category_id
          WHERE name LIKE '% :nameSearch %'";

$results = DB::select(DB::raw($query), ['nameSearch' => 'ger']);

second way used like that 那样使用第二种方式

$searchText = "ger";
$results = DB::select(DB::raw($query), ['nameSearch' => "%".$searchText."%"]);

You need to add the % 's to the bind value and not in the query (unless you concat() the values)... 您需要将% s添加到绑定值中,而不是在查询中(除非您concat()值)...

$query = "SELECT 1 AS rank, 'CATEGORY' AS type, category_id AS id, name AS name
          FROM category_translations
          JOIN categories ON categories.id = category_translations.category_id
          WHERE name LIKE ?";

$results = DB::select($query, ['%ger%']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM