php Laravel 4 - 连接到其他数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17410049/
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
Laravel 4 - Connect to other database
提问by TheNiceGuy
I want to connect to another database sometimes.
有时我想连接到另一个数据库。
I created a config.php with the database connection data.
我用数据库连接数据创建了一个 config.php。
But how can i tell laravel to connect to this database insted of using the config/database.php?
但是我怎么能告诉 laravel 连接到这个数据库,而不是使用 config/database.php 呢?
For example when using the Schema
class.
例如在使用Schema
类时。
Since no one seems to understand what i want.
因为似乎没有人明白我想要什么。
I DON'T want to use the config/database.php, i want to use a different config file on a different location.
我不想使用 config/database.php,我想在不同的位置使用不同的配置文件。
回答by fideloper
It sounds like you figured this out. Here's how I'd accomplish it anyway for other people coming in, or in case something useful is here for you.
听起来你已经明白了这一点。这是我无论如何都会为其他人完成它的方法,或者如果有一些有用的东西对你有用。
First, Add a second connection in app/config/database.php
. Note: That file path may change depending on your environment.
首先,在 中添加第二个连接app/config/database.php
。注意:该文件路径可能会根据您的环境而改变。
<?php
return array(
'connections' => array(
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database1',
'username' => 'user1',
'password' => 'pass1'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
'mysql2' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database2',
'username' => 'user2',
'password' => 'pass2'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
),
);
Second, in your code, you can use (as mentioned) the 2nd connection where you would like:
其次,在您的代码中,您可以使用(如上所述)您想要的第二个连接:
Schema::connection('mysql2')->create('users', function($table) {})
Schema::connection('mysql2')->create('users', function($table) {})
There's more documentation on this - see Accessing Connections.
有更多关于此的文档 - 请参阅访问连接。
Eloquent ORMYou can define the variable for "connection" in an eloquent class to set which connection is used. That's noted in the Basic Usagesection.
Eloquent ORM您可以在 eloquent 类中为“连接”定义变量以设置使用哪个连接。这在基本用法部分有说明。
See that variable on here on Githuband the method which you can set to set the connection dynamically here.
查看该变量在这里Github上,并且可以设置动态设置连接的方法在这里。
EditThe OP has made it clear that they do not wish to use the config/database.php file for config.
编辑OP 已经明确表示他们不希望使用 config/database.php 文件进行配置。
However without explaining further, I can't comment. I'm happy to help - sounds like it would be useful to know whythe config/database.php file can't/shouldn't be used, as this can help us ascertain the problem and create a useful solution.
但是,如果不进一步解释,我无法发表评论。我很乐意提供帮助 - 听起来好像知道为什么不能/不应该使用 config/database.php 文件会很有用,因为这可以帮助我们确定问题并创建有用的解决方案。
回答by Sudesh
I believe you want to implement some kind of logical sharding where databases would be dynamically created.
我相信您想实现某种逻辑分片,在其中动态创建数据库。
In such scenario in laravel you can dynamically add a database config, like below
在 Laravel 中的这种情况下,您可以动态添加数据库配置,如下所示
$conn = array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'DATABASE',
'username' => 'USERNAME',
'password' => 'SOME_PASSWORD',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
);
Config::set('database.connections.DB_CONFIG_NAME', $conn);
Now to connect via eloquent
现在通过 eloquent 连接
MODEL::on('DB_CONFIG_NAME')->WHAT_EVER('1');
Incase of Query Builder you can do
Incase Query Builder 你可以做
$DB = DB::connection('DB_CONFIG_NAME');
use $DB->select()
for querying now.
用$DB->select()
现在查询。
Hope this would help devs looking for a possible solution for this question
希望这会帮助开发人员为这个问题寻找可能的解决方案
回答by Phil Sturgeon
Remember that Laravel 4 is actually a collection of components, and you can use these components solo.
请记住,Laravel 4 实际上是一个组件的集合,您可以单独使用这些组件。
https://github.com/illuminate/database
https://github.com/illuminate/database
There is an example here that shows off how interacting with the Capsule class works:
这里有一个例子展示了如何与 Capsule 类进行交互:
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
]);
// Set the event dispatcher used by Eloquent models... (optional)
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));
// Set the cache manager instance used by connections... (optional)
$capsule->setCacheManager(...);
// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();
// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();
This is a bunch of bootstrapping that you'll need to run, so tuck it away somewhere in a function or method.
这是一堆你需要运行的引导,所以把它藏在函数或方法的某个地方。
But, its absolutely possible.
但是,绝对有可能。
回答by na-98
There is a simpler solution. If you are using Larave 4 there is an option that worked for me. Recently they added $table variable that you can specify in your model. Refer to this link.
有一个更简单的解决方案。如果您使用的是 Larave 4,那么有一个选项对我有用。最近他们添加了您可以在模型中指定的 $table 变量。请参阅此链接。
class User extends Eloquent {
protected $table = 'my_users';
}
If you are using MySQL, you can do the following:
如果您使用的是 MySQL,您可以执行以下操作:
class User extends Eloquent {
protected $table = 'mydbname.my_users';
}
If you are using SQL Server, you can do this:
如果您使用的是 SQL Server,则可以执行以下操作:
class User extends Eloquent {
protected $table = 'mydatabase..my_users';
}
My Config file had DB1 specified but I created a model which wants to access DB2 in the same MySQL host. So this was a quick and dirty way to accomplish this.
我的配置文件指定了 DB1,但我创建了一个模型,该模型想要访问同一 MySQL 主机中的 DB2。所以这是一种快速而肮脏的方式来实现这一点。
Now I don't fully leverage Eloquent ORM all the time so this "hack" may not work with Many to Many or one to Many Eloquent methods.
现在我不会一直充分利用 Eloquent ORM,所以这个“hack”可能不适用于多对多或一对多 Eloquent 方法。
One another idea I had but I didn't actually try was creating a stored procedure (routine) in DB1 and inside of that routine I can access DB2 tables by querying link this:
我有但实际上没有尝试的另一个想法是在 DB1 中创建一个存储过程(例程),在该例程中,我可以通过查询链接来访问 DB2 表:
SELECT * from db2.mytable where id = 1;
回答by sturrockad
To use a config file in another location, say src/config
:
要在另一个位置使用配置文件,请说src/config
:
use Config;
$this->dbConfig = Config::get('appname::dbInfo.connections.test');
$this->database = $this->dbConfig['database'];
$this->username= $this->dbConfig['username'];
$this->password= $this->dbConfig['password'];
Where dbInfo
is a simple php file in your app's src/config
directory returning an array containing the element connections
which is an array of database properties.
dbInfo
应用程序src/config
目录中的简单 php 文件在哪里返回一个包含元素的数组,该元素connections
是一个数据库属性数组。
You can tell Laravel to use an external config file using:
您可以使用以下命令告诉 Laravel 使用外部配置文件:
Config::set("database.connections.test", $this->dbConfig);
DB::connection("test");
回答by Eduardo Stuart
Edit bootstrap/start.php
file and add your machine name (open terminal: hostname
).
编辑bootstrap/start.php
文件并添加您的机器名称(打开终端:)hostname
。
Add your machine to $env,
将您的机器添加到 $env,
$env = $app->detectEnvironment(array(
'mymachine' => array('mymachine.local'),
));
- Create a new path at
'app/config/mymachine'
- Add a copy of
database.php
with new config params.
- 创建一个新路径在
'app/config/mymachine'
- 添加
database.php
带有新配置参数的副本。