[英]Laravel database select method issue with spaces in table name?
我試圖通過DB類查詢遠程數據庫連接,並且在傳遞參數作為表名時遇到問題。
這有效並返回預期結果:
$result = DB::connection('remote')->select('select * from "Users who can post batch"');
但是,這些語句不:
// $view->name returns; string(34) "Users who can post batch"
$result = DB::connection('remote')->select('select * from ?', array( $view->name ));
$result = DB::connection('remote')->select('select * from "?"', array( $view->name ));
$result = DB::connection('remote')->select('select * from [?]', array( $view->name ));
$result = DB::connection('remote')->select('select * ' . $view->name );
我收到此錯誤:
SQLSTATE[HY000]: General error: 102 General SQL Server error: Check messages from the SQL Server
[102] (severity 15) [(null)] (SQL: select * from ?) (Bindings: array ( 0 => 'Users who can post batch', ))
我究竟做錯了什么?
Laravel數據庫文檔: http ://laravel.com/docs/database
您從一個沒有告訴您所有內容的頁面獲得了答案。 不要直接在純文本中使用查詢。 通常,您應該嘗試使用QueryBuilder創建查詢,但是,當然,如果不可能,請至少使用DB :: raw()創建查詢:
$result = DB::connection('remote')->select(DB::raw('select * from "' . $view->name . '"'));
Laravel將轉義您的查詢以防止SQL注入。
使用參數,我已經為您看到的正確版本是您已經嘗試過的:
$result = DB::connection('remote')->select(DB::raw('select * from "?"'), array($view->name));
但是,使用SQL Server,事情並不能完全按照我們的預期進行。 因此,看一下您的服務器日志,您可能會在這里找到問題的根源:
SELECT t.[text]
FROM sys.dm_exec_cached_plans AS p
CROSS APPLY sys.dm_exec_sql_text(p.plan_handle) AS t
WHERE t.[text] LIKE N'%something unique about your query%';
DB :: raw這是您添加更多參數的方式
$result = DB::connection('remote')->select(DB::raw('select * from "' . $view->name . '" where id = ?', array(1)'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.