change database connection in laravel model

2019-02-17 18:38发布

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 :

<?php
class McibModel extends Eloquent {
    /**
      * The database table used by the model.
      *
      * @var string
      */
    //here i should call the external database table
    protected $table = 'agencies';
}

So please if someone has any idea i will be very appreciative.

1条回答
啃猪蹄的小仙女
2楼-- · 2019-02-17 19:04

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'    => '',
        ),
    ),
查看更多
登录 后发表回答