Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

php - Laravel 4 - Connect to other database

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 database insted of using the config/database.php?

For example when using the Schema class.

Since no one seems to understand what i want.

I DON'T want to use the config/database.php, i want to use a different config file on a different location.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...