简体   繁体   English

Laravel数据库选择方法问题与表名中的空格?

[英]Laravel database select method issue with spaces in table name?

I'm attempting to query a remote database connection via the DB class, and am having issues passing a parameter as table name. 我试图通过DB类查询远程数据库连接,并且在传递参数作为表名时遇到问题。

This works and returns expected results: 这有效并返回预期结果:

$result = DB::connection('remote')->select('select * from "Users who can post batch"');

However, these statements do not: 但是,这些语句不:

// $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 );

I receive this error: 我收到此错误:

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', ))

What am I doing wrong? 我究竟做错了什么?

Resources 资源资源

Laravel database documentation: http://laravel.com/docs/database Laravel数据库文档: http ://laravel.com/docs/database

You got your answer from a page which is not telling you everything. 您从一个没有告诉您所有内容的页面获得了答案。 Don't use queries in plain text directy. 不要直接在纯文本中使用查询。 Normally you should try to use QueryBuilder to create your queries, but, of course, if it's not possible, at least use DB::raw() to create them: 通常,您应该尝试使用QueryBuilder创建查询,但是,当然,如果不可能,请至少使用DB :: raw()创建查询:

$result = DB::connection('remote')->select(DB::raw('select * from "' . $view->name . '"'));

Laravel will escape your queries to prevent sql injection. Laravel将转义您的查询以防止SQL注入。

Using parameters, the correct version I see for your is something you already tried: 使用参数,我已经为您看到的正确版本是您已经尝试过的:

$result = DB::connection('remote')->select(DB::raw('select * from "?"'), array($view->name));

But, with SQL Server, things doesn't work exactly how we think they should. 但是,使用SQL Server,事情并不能完全按照我们的预期进行。 So, take a look a your server logs, you might find the source of the problem there: 因此,看一下您的服务器日志,您可能会在这里找到问题的根源:

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.

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