沃梦达 / 编程问答 / php问题 / 正文

Laravel 4 - 连接到其他数据库

Laravel 4 - Connect to other database(Laravel 4 - 连接到其他数据库)

本文介绍了Laravel 4 - 连接到其他数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时想连接到另一个数据库.

I want to connect to another database sometimes.

我用数据库连接数据创建了一个config.php.

I created a config.php with the database connection data.

但是我怎样才能告诉 laravel 使用 config/database.php 连接到这个数据库呢?

But how can i tell laravel to connect to this database insted of using the config/database.php?

例如在使用 Schema 类时.

因为似乎没有人明白我想要什么.

Since no one seems to understand what i want.

我不想使用 config/database.php,我想在不同的位置使用不同的配置文件.

推荐答案

听起来你想通了.无论如何,如果其他人进来,或者如果有什么对你有用的东西,这就是我将如何完成它.

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.

首先,在app/config/database.php中添加第二个连接.注意:该文件路径可能会根据您的环境而变化.

First, Add a second connection in app/config/database.php. Note: That file path may change depending on your environment.

<?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) {})

关于此的更多文档 - 请参阅 访问连接.

There's more documentation on this - see Accessing Connections.

雄辩的 ORM您可以在 eloquent 类中定义连接"的变量来设置使用哪个连接.基本用法部分对此进行了说明.

Eloquent ORM You can define the variable for "connection" in an eloquent class to set which connection is used. That's noted in the Basic Usage section.

在 这里查看该变量Github 以及您可以设置动态设置连接的方法 这里.

See that variable on here on Github and the method which you can set to set the connection dynamically here.

编辑OP 已经明确表示他们不希望使用 config/database.php 文件进行配置.

Edit The OP has made it clear that they do not wish to use the config/database.php file for config.

但是,如果没有进一步解释,我无法发表评论.我很乐意提供帮助 - 知道为什么不能/不应该使用 config/database.php 文件听起来很有用,因为这可以帮助我们确定问题并创建一个有用的解决方案.

However without explaining further, I can't comment. I'm happy to help - sounds like it would be useful to know why the config/database.php file can't/shouldn't be used, as this can help us ascertain the problem and create a useful solution.

这篇关于Laravel 4 - 连接到其他数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Laravel 4 - 连接到其他数据库

基础教程推荐