Laravel 数据库:连接多个 MySQL 数据库 1 个改进

第一步、定义数据库链接

config/database.php

<?php
return [

    'default' => 'mysql',

    'connections' => [

        # 主要数据库连接
        'mysql' => [
            'driver'    => 'mysql',
            'host'      => 'host1',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1',
            'charset'   => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix'    => '',
        ],

        # 第二个链接
        'mysql2' => [
            'driver'    => 'mysql',
            'host'      => 'host2',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2',
            'charset'   => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix'    => '',
        ]
    ],
];

第二步、连接第二个数据库

我们已经成功配置了第二个数据库链接,接下来讲解几种连接的方法。

1. Schema 表结构更改

在代码迁移时,可以使用 Schema 提供的 connection() 方法:

Schema::connection('mysql2')->create('some_table', function($table)
{
    $table->increments('id'):
});

2. Query 数据库查询

同样的,数据库查询构造器里提供了一个 connection() 方法:

$users = DB::connection('mysql2')->select(...);

3. Eloquent 数据模型

使用 $connection 属性来设置默认的连接:

<?php

class SomeModel extends Eloquent {

    protected $connection = 'mysql2';

}

你也可以使用 setConnection 来动态设置连接:

<?php

class SomeController extends BaseController {

    public function someMethod()
    {
        $someModel = new SomeModel;

        $someModel->setConnection('mysql2');

        $something = $someModel->find(1);

        return $something;
    }

}

或者使用 on() 方法:

$someModel->on('mysql2')->find(1);
本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 8

在join 查询中如何 连接多个数据库跨库查询呢?

5年前 评论

@vopdoo 貌似没这样玩过,

5年前 评论

@vopdoo 可以使用这种连接$users = DB::connection('mysql2')->select(...);

5年前 评论

@vopdoo 不能跨库的话,分开查询,先从一个库查询出结果,把结果集放到另外一个库查询也可以的吧

5年前 评论

sqlsrv 这样操作连不上第二个数据库 :cry: :cry: :cry:

4年前 评论

如果是游戏服的数据库,会有很多个,都要配上去吗?新手..不知道怎么解决 就点击某个单服,就要连接到对应的那个单服的数据库

3年前 评论
liaosp 3年前
joyCode 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!