且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获得laravel DB连接到PHP连接?

更新时间:2023-11-18 17:03:40

您可以根据需要在laravel中使用原始查询来执行查询.如果仍然需要连接实例,则可以创建一个类并实现ConnectionResolverInterface:

use Illuminate\Database\ConnectionResolverInterface as Resolver
class connection implements Resolver {

}

然后您可以建立连接:

$connector = new connection();
$connection = $connector->connection();

如果您正在使用模型连接,则可以通过以下方式获得连接:

$user = new User();
$user->getConnection();

还可以使用ConnectionFactory建立新连接:

$connection = new Illuminate\Database\Connector\ConnectionFactory();

有关更多信息,请参见 laravel API文档 >

I need to receive laravel DB connection to variable to make concrete pure SQL php demands on a database. Desired code:

<?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)

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.

DB::connection()->name

returns a name of DB, but thats no connection :/

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)

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:

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:

$connection = new Illuminate\Database\Connector\ConnectionFactory();

for more information you can see laravel API doc