如何获得 Laravel DB 连接到 php 连接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43023458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get laravel DB connection to php connection?
提问by Marek Bernád
I need to receive laravel DB connection to variable to make concrete pure SQL php demands on a database. Desired code:
我需要接收到变量的 laravel DB 连接,以对数据库提出具体的纯 SQL php 需求。所需代码:
<?php
// this is not working
$conn = DB::connection();
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Desired result: "Connected successully"
预期结果:“成功连接”
I need it because I have very complex SQL demands that I need to put in one query, not using laravel query syntax (I believe it is better approach, but I have complex queries and need to use pure query text to execute, not laravel "->" syntax)
我需要它,因为我有非常复杂的 SQL 需求,我需要放入一个查询中,而不是使用 laravel 查询语法(我相信这是更好的方法,但我有复杂的查询,需要使用纯查询文本来执行,而不是 laravel” ->" 语法)
I need to get laravel DB connection to not always often establish second php connection like with PDO or writing down DB credentials. If PDO connection to DBS from laravel exists, it could be useful to obtain to php for me too.
我需要获得 laravel 数据库连接,而不是总是像使用 PDO 或写下数据库凭据那样经常建立第二个 php 连接。如果存在从 laravel 到 DBS 的 PDO 连接,那么获取 php 对我来说也很有用。
DB::connection()->name
returns a name of DB, but thats no connection :/
返回 DB 的名称,但没有连接:/
I was looking for it but nowhere found solution for that, could someone help me find correct answer please? (maybe it is not important, but I use mysql)
我正在寻找它,但没有找到解决方案,有人可以帮我找到正确的答案吗?(也许不重要,但我用的是mysql)
采纳答案by MoPo
You can use raw query in laravel for executing queries as you wish. If you need connection instance anyway you can create a class and implement ConnectionResolverInterface:
您可以在 laravel 中使用原始查询来根据需要执行查询。如果您仍然需要连接实例,您可以创建一个类并实现 ConnectionResolverInterface:
use Illuminate\Database\ConnectionResolverInterface as Resolver
class connection implements Resolver {
}
then you can get connection:
然后你可以得到连接:
$connector = new connection();
$connection = $connector->connection();
If you're using your model connection you can get connection this way:
如果您使用的是模型连接,则可以通过以下方式获得连接:
$user = new User();
$user->getConnection();
Also you can make a new connection by using ConnectionFactory:
您也可以使用 ConnectionFactory 建立新连接:
$connection = new Illuminate\Database\Connector\ConnectionFactory();
for more information you can see laravel API doc
有关更多信息,您可以查看laravel API 文档