如何为雄辩的人设置现有连接

问题描述 投票:0回答:1

我们正在将旧版应用程序迁移到流明。该应用程序使用事务。如何将现有连接设置为雄辩地执行事务中orm的sql。

该连接由自定义数据库类处理,并由pg_connect()创建。

模型的setConnection方法仅接受用于配置数据库连接的字符串。资源无法传递。

如何将手动创建的连接对象设置为orm?

php eloquent transactions database-connection lumen
1个回答
0
投票

假设您正在谈论PDO连接,您需要在所讨论的模型上设置一个连接解析器,使用User::class查看此示例

// setup
$databaseName = 'my_database_name';
$tablePrefix = '';
$pdo = new PDO("mysql:host=127.0.0.1;dbname=$databaseName", 'root', '');
$container = new \Illuminate\Container\Container(); // you should use the app container, this is just a placeholder

// 1st step - we need to create a custom factory to expose the base method responsible for doing the work under the hood
$customFactory = new class($container) extends \Illuminate\Database\Connectors\ConnectionFactory
{
    /**
     * @param PDO    $pdo
     * @param string $database
     * @param string $prefix
     * @return \Illuminate\Database\Connection
     */
    public function makeConnection(PDO $pdo, $database, $prefix = '')
    {
        return $this->createConnection($pdo->getAttribute(PDO::ATTR_DRIVER_NAME), $pdo, $database, $prefix);
    }
};

// 2nd - we use the method that we just created to convert the PDO instance into a Laravel connection
$connection = $customFactory->makeConnection($pdo, $databaseName, $tablePrefix);

// 3rd - we need to configure our connection resolver, you can use the above method to create you own instance, or you can use the one provided by the container
$resolver = new \Illuminate\Database\ConnectionResolver();
$resolver->addConnection('custom', $connection);
$resolver->setDefaultConnection('custom');

// 4th - assign the resolver to your model 
User::setConnectionResolver($resolver);

// 5th - profit
dump(User::all());
© www.soinside.com 2019 - 2024. All rights reserved.