change database connection in laravel model

前端 未结 4 1568
面向向阳花
面向向阳花 2020-12-09 03:57

So i work with Laravel 4.2, what i want is in one of my models use an external database, this is my model code :



        
4条回答
  •  [愿得一人]
    2020-12-09 04:52

    Different models can have different database connections. So your models use the normal default connection - but your 'McibModel' model can use another connection:

    class McibModel extends Model {
    
        protected $connection= 'second_db_connection';
    
        protected $table = 'agencies';
    
    }
    

    Then in your DB connection file - you would have something like this:

    return array(
        'connections' => array(
            'mysql' => array(
                'driver'    => 'mysql',
                'host'      => 'localhost',
                'database'  => 'database1',
                'username'  => 'user1',
                'password'  => 'pass1'
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => '',
            ),
    
            'second_db_connection' => array(
                'driver'    => 'mysql',
                'host'      => 'localhost',
                'database'  => 'database2',
                'username'  => 'user2',
                'password'  => 'pass2'
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => '',
            ),
        ),
    

提交回复
热议问题