在Eloquent模型上还有另一种“setConnection”的方法吗?

时间:2016-12-21 22:15:23

标签: php mysql laravel-5 eloquent

我目前正在处理一个“动态交换连接的多数据库”项目。

所以我最终做的是以下内容:

$connectionName = uniqid();
\Config::set('database.connections.' . $connectionName, [/** db options **/]);
\Artisan::call('migrate', ['--database' => $connectionName]);

$connectionName = uniqid();           
\Config::set('database.connections.' . $connectionName,[/** db options **/]);

$user = new User();
$user->setConnection($connectionName);
$user->first_name = 'Daisy';
$user->last_name = 'Demo';
$user->is_not_being_ignored_by_santa_this_year = 0;
$user->email = //and so so on
$user->save();

对于Artisan调用,我有点理解为什么Laravel需要引用字符串中的连接,保存在配置数组中。

然而,在Eloquent Model本身,我发现将数据库连接写入配置数组有点麻烦。所以它可以通过模型中的“Singleton方法”\ Config :: get()..来获取。

是否有更优雅的东西,我可以直接注入配置而无需将其写入某些超级全局?

或者我错过了什么?

4 个答案:

答案 0 :(得分:11)

你可能会更好creating a configuration array for each connection,然后你可以通过指定要使用的连接轻松地在连接之间切换。

如果您需要在同一型号上使用多个连接,可以使用on method

所以它会像User::on('dbconnection2')->find(1)

如果您只想为不同的模型使用不同的连接,可以在模型上设置受保护的$connection属性:

class User extends Model
{
    protected $connection = 'dbconnection2';
}

希望有所帮助。

答案 1 :(得分:2)

您可以为模型创建工厂,并在引导您的应用时将连接传递给它:

<?php

class ModelFactory
{
    private $db;

    public function __construct($dbConnection)
    {
        $this->db = $dbConnection;
    }

    public function createNewModel($class)
    {
        $object = new $class();
        $object->setConnection($this->db);
        return $object;
    }
}

然后在你的代码中:

$user = $factory->createModel(User::class);

像这样的东西!祝好运! : - )

答案 2 :(得分:2)

我构建了一个多租户laravel应用程序,但感到惊讶的是,没有做到这一点的现成方法。

我有一个可以通过不同子域使用的应用程序,并且该子域应该是不同配置(例如数据库连接)的关键。

您可以轻松地使其适应所需的任何条件,而不是子域。

通过动态Config :: set()

因此,我的第一个尝试是始终使用“默认”连接,并创建一个动态调用Config::set("database.connection.default.host", "1.3.5.7");等所有其他设置的中间件。

但是有一些缺点。例如,这很慢,因为我从数据库中读取了所有值,然后从redis中读取了所有值。但是更大的问题是,例如,设置与redis缓存的连接,因为redis连接已经在它调用的中间件覆盖配置设置之前建立了。

通过自己的配置文件

因此,我的第二个也是当前的方法是通过配置文件来全部实现。因此,我创建了以下文件结构:

  • config / _myapp.php
  • config / subdomain1 / _myapp.php

注意:下划线很重要,因为文件是按字母顺序读取的,并且必须首先读取我们的新文件才能在其他配置文件中使用它。

目标是使用config('_myapp.DB_HOST')从config / [subdomain] / _ myapp.php中检索DB_HOST值,并将其用作config / database.php中的值。 因此config / _myapp.php仅返回特定子域的_myapp.php内容。

config / _myapp.php中的

:     

// get the current subdomain from $_SERVER['HTTP_HOST']
$subdomain = \App\Helper::getSubDomain();

define('SUBDOMAIN', $subdomain);

if(!empty($subdomain) && file_exists($file = __DIR__."/$subdomain/".basename(__FILE__)))
    return require($file);

return [

];

和config / _myapp.php中的

return [
    ...
    'DB_HOST' => '1.3.5.7',
    ...
];

例如在config / database.php或需要域特定配置的任何地方使用此选项:

...
   'host' => config('_myapp.DB_HOST'),
...

请问是否有任何问题,花了我很多时间弄清这些东西。

答案 3 :(得分:1)

这一切都取决于你如何处理你的多个连接。我已经从事类似的需求项目。

  • 我们有主从/租户数据库连接。配置https://gist.github.com/safoorsafdar/c6c623f9ec7b440f563d76995faf7aec#file-database-php
  • 租户数据库/迁移/种子在系统中创建新帐户即时创建
  • 可以从根控件中删除数据库。
  • 在用户登录时,我们检查其是否为主,连接到主连接否则获得租户连接,在会话中存储信息以进行Web访问。检查Tenant Setup after login
  • 数据库连接相关的操作中心类。查看DatabaseConnection
  • 中心租户会话处理程序类,以帮助解析会话中的租户ID。查看TenantContextSession
  • 我们为租户和主人设有抽象类的单独模型,以设置模型连接。检查
  • 您可能还需要在系统中处理迁移,请仔细研究 https://gist.github.com/safoorsafdar/cc9252a2f14301c3da942ca7bec7d66e

租户模型摘要类

<?php

namespace App\Models\Abstracts;

use App\Models\Abstracts\AbstractBaseModel;
use App\Models\Picklist\PicklistValue;

class TenantAbstractBaseModel extends AbstractBaseModel
{
    function __construct(array $attributes = array())
    {
        parent::__construct($attributes);
        if ( ! is_null(app('tenant.context')->getConnectionName())) {
            $this->setConnection(app('tenant.context')->getConnectionName());
        }

        //todo; should be dynamic
        if (is_null(app('tenant.context')->getConnectionName())
            && app()->runningInConsole()
        ) {
            //todo; need to resolve database connection through terminal and application.
            //dd(config('tenant.tenant_connection'));
            //$this->setConnection(config('tenant.tenant_connection'));
        }

    }
}

登录后的租户设置

$connection = config('tenant.tenant_connection');
                //config()->set('database.default', config('tenant.tenant_connection'));
            app('tenant.context')->setConnectionName($connection);
            app('tenant.context')->setTenantId($company_id);

             //$database = config('database.connections.' . $connection . '.database') . $company_id;
             $company_system_name
                    = $this->auth->user()->company->system_name;
             config()->set('database.connections.'.$connection.'.database',
                    $company_system_name);
             //config()->set('database.connections.' . $connection . '.database', $database);
           config()->set('database.default', $connection);

DatabaseConnection

<?php

namespace App\Tenancy\Tenant;

use Config;
use DB;
use App\Tenancy\Exceptions\TenantDatabaseException;
use App\Tenancy\Models\Tenant;

/**
 * Class DatabaseConnection
 *
 * Helps with tenant database connections
 */
class DatabaseConnection
{
    /**
     * See the multi-tenant configuration file. Configuration set
     * to use separate databases.
     */
    const TENANT_MODE_SEPARATE_DATABASE = 'database';

    /**
     * See the multi-tenant configuration file. Configuration set
     * to use prefixed table in same database.
     */
    const TENANT_MODE_TABLE_PREFIX = 'prefix';
    /**
     * Current active global tenant connection.
     *
     * @var string
     */
    protected static $current;
    /**
     * @var string
     */
    public $name;
    /**
     * @var Tenant
     */
    protected $tenant;
    /**
     * @var \Illuminate\Database\Connection
     */
    protected $connection;

    public function __construct(Tenant $tenant)
    {
        $this->tenant = $tenant;

        $this->name = "tenant.{$this->tenant->hash_id}";

        $this->setup();
    }

    /**
     * Sets the tenant database connection.
     */
    public function setup()
    {
        Config::set("database.connections.{$this->name}", $this->config());
    }

    /**
     * Generic configuration for tenant.
     *
     * @return array
     */
    protected function config()
    {
        $clone             = Config::get(sprintf('database.connections.%s',
            static::tenantConnectionName()));
        $clone['database'] = $this->tenant->system_name;

        return $clone;
    }

    /**
     * Central getter for system connection name.
     *
     * @return string
     */
    public static function systemConnectionName()
    {
        return Config::get('tenant.master_connection', 'mysql');
    }

    /**
     * Checks whether current connection is set as global tenant connection.
     *
     * @return bool
     */
    public function isCurrent()
    {
        return $this->name === static::getCurrent();
    }

    /**
     * Loads the currently set global tenant connection name.
     *
     * @return string
     */
    public static function getCurrent()
    {
        return static::$current;
    }

    /**
     * Sets current global tenant connection.
     */
    public function setCurrent()
    {
        static::$current = $this->name;
        Config::set(sprintf('database.connections.%s',
            static::tenantConnectionName()), $this->config());

        DB::purge(static::tenantConnectionName());
    }

    /**
     * Central getter for tenant connection name.
     *
     * @return string
     */
    public static function tenantConnectionName()
    {
        return Config::get('tenant.tenant_connection', 'tenant_mysql');
    }

    /**
     * Loads connection for this database.
     *
     * @return \Illuminate\Database\Connection
     */
    public function get()
    {
        if (is_null($this->connection)) {
            $this->setup();
            $this->connection = DB::connection($this->name);
        }

        return $this->connection;
    }

    /**
     * @return bool
     */
    public function create()
    {
        $clone = $this->config();

        return DB::connection(static::systemConnectionName())
            ->transaction(function () use ($clone) {
                if ( ! DB::connection(static::systemConnectionName())
                    ->statement("create database if not exists `{$clone['database']}`")
                ) {
                    throw new TenantDatabaseException("Could not create database {$clone['database']}");
                }
                if ( ! DB::connection(static::systemConnectionName())
                    ->statement("grant all on `{$clone['database']}`.* to `{$clone['username']}`@'{$clone['host']}' identified by '{$clone['password']}'")
                ) {
                    throw new TenantDatabaseException("Could not create or grant privileges to user {$clone['username']} for {$clone['database']}");
                }

                return true;
            });
    }

    /**
     * @throws \Exception
     *
     * @return bool
     */
    public function delete()
    {
        $clone = $this->config();

        return DB::connection(static::systemConnectionName())
            ->transaction(function () use ($clone) {
                if ( ! DB::connection(static::systemConnectionName())
                    ->statement("revoke all on `{$clone['database']}`.* from `{$clone['username']}`@'{$clone['host']}'")
                ) {
                    throw new TenantDatabaseException("Could not revoke privileges to user {$clone['username']} for {$clone['database']}");
                }
                if ( ! DB::connection(static::systemConnectionName())
                    ->statement("drop database `{$clone['database']}`")
                ) {
                    throw new TenantDatabaseException("Could not drop database {$clone['database']}");
                }

                return true;
            });
    }
}

* TenantContextSession *

<?php

namespace App\Repositories\Tenant;

use App\Repositories\Tenant\TenantContextRepositoryContract;

/**
 * Description of TenantContextSession
 *
 * @author safoor
 */
class TenantContextSession implements TenantContextRepositoryContract
{
//    public function __construct() {
//        $this->clearTenantSession();
//    }

    /**
     * Sets the connection name for the actual context
     * this tenant
     * @param $name
     * @return mixed
     */
    public function setConnectionName($name)
    {
        if (session()->has('tenant_connection')) {
            session()->set('tenant_connection', '');
        }

        session()->put('tenant_connection', $name);
    }

    /**
     * Get the name of the current connection in context
     * @return mixed
     */
    public function getConnectionName()
    {
        return session()->get('tenant_connection');
    }

    /**
     * Sets the id value filter data in the current context
     * @param $id
     * @return mixed
     */
    public function setTenantId($id)
    {
        if (session()->has('tenant_id')) {
            session()->set('tenant_id', '');
        }
        session()->put('tenant_id', $id);
    }

    /**
     *
     * @return mixed
     */
    public function getTenantId()
    {
        return session()->get('tenant_id');
    }

    public function clearTenantSession()
    {
        session()->flush();
        session()->set('tenant_id', '');
        session()->set('tenant_connection', '');
    }
}

我希望这将有助于您的方案,我试图提到我们必须涵盖的所有方面,但如果仍然有一些令人困惑的事情需要我的解释,请告诉我。