php 在 Laravel 模型中更改数据库连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28985472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:11:33  来源:igfitidea点击:

change database connection in laravel model

phplaravellaravel-4

提问by Mohammed Hassar

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

所以我使用Laravel 4.2,我想要的是在我的模型之一中使用外部数据库,这是我的模型代码:

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

所以,如果有人有任何想法,我将不胜感激。

回答by Laurence

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

不同的模型可以有不同的数据库连接。所以您的模型使用正常的默认连接 - 但您的“McibModel”模型可以使用另一个连接:

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'    => '',
        ),
    ),

回答by willsmanley

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');

回答by Jed Lynch

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();