change database connection in laravel model

前端 未结 4 1567
面向向阳花
面向向阳花 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:41

    I think for a lot of use cases it can be convenient to declare the connection at runtime like this:

    $McibModel = new McibModel();
    $McibModel->setConnection('second_db_connection');
    
    0 讨论(0)
  • 2020-12-09 04:50

    In one way setting a protected property will always connect a particular model to a database.

    class MyModel extends Model {
    
         protected $connection = "second_db_connection";
    }
    

    In a query I like this approach...

    (new MyModel())->on('second_db_connnection')->get();
    
    0 讨论(0)
  • 2020-12-09 04:51

    You can do it like this to set another connection :

    $product= new Product();
    $product->setConnection('another_connection');
    
    0 讨论(0)
  • 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'    => '',
            ),
        ),
    
    0 讨论(0)
提交回复
热议问题