Slim Framework with ORM (Eloquent) 连接多个数据库

Slim Framework with ORM (Eloquent) connect multiple db

我正在使用带有 Eloquent 4.1.x 的 Slim Framework 作为项目的 ORM,并且需要连接到多个数据库。

我按照这个 link 设置了 ORM。但是如何按照给定的教程连接到多个数据库?

在我的模型中,我有不同的文件用于不同数据库中的不同 table。

像 User.php 文件有以下内容,

<?php
namespace Service\Framework\Model;

use Illuminate\Database\Eloquent\Model;

class Users extends Model {
  protected $table = 'users';
}

此 class 使用 db_2 数据库中的用户 table。我想在此 Class 中的一个方法中从默认数据库 db_1 切换。喜欢,

<?php

namespace Service\Framework\Model;

use Illuminate\Database\Eloquent\Model;

class Users extends Model {
  protected $table = 'users';

  public function getUsers() {
    // Switch the database to db_2
    $users = self::all();
    // Again switch back to default database db_1
    return $users;
  }
}

我该怎么做?请帮我提点建议。

P.S: 我这里没有使用Capsule

编辑 #1 所以我用来设置单个连接的代码如下,

$settings = array(
      'driver' => 'mysql',
      'host' => 'localhost',
      'database' => 'db_1',
      'username' => 'dbuser',
      'password' => 'password',
      'charset'  => 'utf8',
      'collation' => 'utf8_general_ci',
      'prefix' => ''
    );

    // Bootstrap Eloquent ORM
    $container = new Container();
    $connFactory = new ConnectionFactory($container);
    $conn = $connFactory->make($settings);
    $resolver = new ConnectionResolver();
    $resolver->addConnection('default', $conn);
    $resolver->setDefaultConnection('default');
    Model::setConnectionResolver($resolver);

首先你应该设置多个连接。建立连接后,您可以指示模型使用 $connection 属性.

的特定连接
namespace Service\Framework\Model;

use Illuminate\Database\Eloquent\Model;

class Users extends Model {
  protected $connection = 'mysql2';
  protected $table = 'users';
}

在路由或控制器中,您可以使用 setConnection() 方法。

$user = new User;
$user->setConnection('mysql2');
print_r($user->find(1));

您可以使用以下简化代码连接到多个数据库:

$app = new \Slim\App([
    'db' => [
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'products',
        'username'  => 'user',
        'password'  => 'pass',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ],
    'db_second' => [
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'second',
        'username'  => 'user',
        'password'  => 'pass',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ],
]);

$container = $app->getContainer();

// connect to db with Illuminate larvel
$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection($container['settings']['db']);
$capsule->addConnection($container['settings']['db_second'], 'db_second');
$capsule->setAsGlobal();
$capsule->bootEloquent();
/// END connect to db

// to accsess the $capsule with our container from our controllers
$container['db'] = function($container) use ($capsule){
    return $capsule;
};

并在模型文件中输入:

protected $connection = 'db_second';