php - Laravel Raw SQL 查询命名参数绑定(bind)顺序

标签 php mysql laravel

“order by”上的命名参数绑定(bind)不适用于此完整的原始语句。不显示错误消息。开始和长度工作。

    $sql = "SELECT
                product.id AS 'product-id',
                product.name AS 'product-name',
                product.status AS 'product-status',
                product.ingredients 'product-ingredients',
                product.price AS 'product-price',
                category.name AS 'category-name'
            FROM
                product
            LEFT JOIN
                category ON product.category_id = category.id
            ORDER BY :orderBy
            LIMIT :start,:length";

    return DB::select($sql, [
        'orderBy' => $orderBy,
        'start' => $start,
        'length' => $length
    ]);

有什么想法吗?

最佳答案

问题出在底层 PDO 语句中。您不能像绑定(bind)值那样在查询中绑定(bind)表名或列名。看到这个答案:

Can PHP PDO Statements accept the table or column name as parameter?

您可以在没有原始表达式的情况下重写您的查询:

return DB::table('product')
           ->select([
               product.id AS 'product-id',
               ...
           ])->leftJoin('category', 'product.category_id', '=', 'category.id')
           ->orderBy($orderBy)
           ->limit($start, $length)

如果您必须使用原始表达式,则必须按值手动清理订单并将其作为字符串插入到查询中。

关于php - Laravel Raw SQL 查询命名参数绑定(bind)顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614131/

相关文章:

mysql - SQL 在连接 3 个表时使用 count 和 sum

PHP 自定义超全局函数

php - zendfox 安装过程中出错,SQLSTATE[HY000] : General error: 1005 (errno: 150)

php - 使用 DOM 和 xpath 设置无样式链接的样式

php - 将特殊字符 ⓄⒼקร 写入/检索到数据库

mysql 子查询 - 结果不同时满足

PHP cli 不使用本地路径(突然)

laravel - 为什么我的 Laravel 项目中的 VS Code 断点不起作用?

php - 如何从一条 laravel 路由获取返回值到另一条路由

PHP 关闭 MySQL 连接