laravel 为模型设置数据库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17784853/
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-09-14 08:10:21  来源:igfitidea点击:

Set database for model?

laravellaravel-4eloquent

提问by Dan

I'm working on a Laravel 4 based site which works over multiple databases. There is one query I need to run on each request that pulls a record from a different database.

我正在一个基于 Laravel 4 的站点上工作,该站点可在多个数据库上运行。我需要对从不同数据库中提取记录的每个请求运行一个查询。

Is there a way I can somehow tie this particular model to the other database so I can just retrieve it as usual?

有没有办法可以将这个特定模型与另一个数据库联系起来,这样我就可以像往常一样检索它?

$client = Client::find(Session::get('client_id'));

Any advice appreciated.

任何建议表示赞赏。

Thanks

谢谢

回答by Andreyco

// Model
class Client extends Eloquent
{
    protected $connection = 'masterDb';
}


// config/database.php
'masterDb' => array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'name',
    'username'  => 'user',
    'password'  => 'pass',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

You can create as many named connections as you wish. Set one of them as default, each model can use any of these connections later.

您可以根据需要创建任意数量的命名连接。将其中一个设置为默认值,以后每个模型都可以使用这些连接中的任何一个。