且构网

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

Laravel 4-连接到其他数据库

更新时间:2022-01-13 22:36:46

听起来您似乎已经明白了.无论如何,这都是我如何为其他人实现的,或者万一有用的东西对您有用.

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 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.