Laravel 4-连接到其他数据库 [英] Laravel 4 - Connect to other database

查看:70
本文介绍了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 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-连接到其他数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆