Laravel 4 - Connect to other database

后端 未结 6 2236
暖寄归人
暖寄归人 2020-12-08 01:25

I want to connect to another database sometimes.

I created a config.php with the database connection data.

But how can i tell laravel to connect to this data

6条回答
  •  心在旅途
    2020-12-08 01:57

    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.

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

     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.

    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.

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

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

    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.

提交回复
热议问题