且构网

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

Laravel 4 - 连接到其他数据库

更新时间:2022-03-21 16:53:53

听起来你想通了.无论如何,如果其他人进来,或者如果有什么对你有用的东西,这就是我将如何完成它.

It sounds like you figured this out. Here's how I'd accomplish it anyway for other people coming in, or in case something useful is here for you.

首先,在app/config/database.php中添加第二个连接.注意:该文件路径可能会根据您的环境而变化.

First, Add a second connection in app/config/database.php. Note: That file path may change depending on your environment.

<?php
return array(
    'connections' => array(
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
    ),
);

第二,在您的代码中,您可以使用(如前所述)您想要的第二个连接:

Second, in your code, you can use (as mentioned) the 2nd connection where you would like:

Schema::connection('mysql2')->create('users', function($table) {})

关于此的更多文档 - 请参阅 访问连接.

There's more documentation on this - see Accessing Connections.

雄辩的 ORM您可以在 eloquent 类中定义连接"的变量来设置使用哪个连接.基本用法部分对此进行了说明.

Eloquent ORM You can define the variable for "connection" in an eloquent class to set which connection is used. That's noted in the Basic Usage section.

这里查看该变量Github 以及您可以设置动态设置连接的方法 这里.

See that variable on here on Github and the method which you can set to set the connection dynamically here.

编辑OP 已经明确表示他们不希望使用 config/database.php 文件进行配置.

Edit The OP has made it clear that they do not wish to use the config/database.php file for config.

但是,如果没有进一步解释,我无法发表评论.我很乐意提供帮助 - 知道为什么不能/不应该使用 config/database.php 文件听起来很有用,因为这可以帮助我们确定问题并创建一个有用的解决方案.

However without explaining further, I can't comment. I'm happy to help - sounds like it would be useful to know why the config/database.php file can't/shouldn't be used, as this can help us ascertain the problem and create a useful solution.