Laravel 4 - Connect to other database

后端 未结 6 2138
暖寄归人
暖寄归人 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:50

    I believe you want to implement some kind of logical sharding where databases would be dynamically created.

    In such scenario in laravel you can dynamically add a database config, like below

    $conn = array(
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'DATABASE',
        'username'  => 'USERNAME',
        'password'  => 'SOME_PASSWORD',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    );
    
    Config::set('database.connections.DB_CONFIG_NAME', $conn);
    

    Now to connect via eloquent

    MODEL::on('DB_CONFIG_NAME')->WHAT_EVER('1');
    

    Incase of Query Builder you can do

    $DB = DB::connection('DB_CONFIG_NAME');
    

    use $DB->select() for querying now.

    Hope this would help devs looking for a possible solution for this question

提交回复
热议问题