还有另一种方法可以"setConnection".在雄辩的榜样上? [英] Is there another way to "setConnection" on an Eloquent Model?
问题描述
我目前正在处理动态交换连接上的多数据库"这类项目.
I am currently handling a "multi db on the fly swap connections" sort of project.
所以我最终要做的是:
$connectionName = uniqid();
\Config::set('database.connections.' . $connectionName, [/** db options **/]);
\Artisan::call('migrate', ['--database' => $connectionName]);
或
$connectionName = uniqid();
\Config::set('database.connections.' . $connectionName,[/** db options **/]);
$user = new User();
$user->setConnection($connectionName);
$user->first_name = 'Daisy';
$user->last_name = 'Demo';
$user->is_not_being_ignored_by_santa_this_year = 0;
$user->email = //and so so on
$user->save();
对于Artisan呼叫,我有点理解为什么Laravel需要引用保存在config数组中的字符串中的连接.
For the Artisan call I sort of understand why Laravel needs to refer to a connection in a string, saved in a config array.
但是,在雄辩模型本身上,我发现必须将数据库连接写入配置数组有点麻烦.因此可以通过模型中的"Singleton方法" \ Config :: get()..来拾取它.
However on the Eloquent Model itself I find it somehow cumbersome to have to write my DB connection into a config array. So it can be picked up by the "Singleton approach" \Config::get().. in the Model.
有没有更优雅的方法,我可以直接注入配置而不必将其写入某些超级全局变量?
Is there something more elegant, where I can inject a configuration directly without having to write it into some super global ?
或者我想念什么吗?
推荐答案
为每个连接创建一个配置数组,然后您可以通过指定要使用的连接来轻松地在连接之间切换.
You would probably be better off creating a configuration array for each connection then you could switch between connections pretty easily by specifying which connection to use.
If you need to use multiple connections on the same model you can use the on
method:
因此它类似于User::on('dbconnection2')->find(1)
如果只想对不同的模型使用不同的连接,则可以在模型上设置受保护的$connection
属性:
If you just want to use different connections for different models, you can set the protected $connection
property on the model:
class User extends Model
{
protected $connection = 'dbconnection2';
}
希望有帮助.
这篇关于还有另一种方法可以"setConnection".在雄辩的榜样上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!