在Laravel 4中即时创建新数据库 [英] Create new database on the fly in Laravel 4

查看:32
本文介绍了在Laravel 4中即时创建新数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动态创建具有特权的新数据库,数据库用户和密码,并在Laravel 4中为每个新用户动态地在新数据库中创建一些表.这是针对多租户网站的.

I want dynamically create new database, database user and password with privileges, create some tables in new database on the fly in Laravel 4 for every new user. This is for a multi tenant website.

什么是最好的解决方案?

Whats the best solution?

谢谢.

推荐答案

这不是您的第一个数据库连接,这很容易,但是由于数据库创建不能用作连接方法,因此您必须执行原始语句:

This is not your first database connection it's easy, but you'll have to execute raw statements because database creation is no available as connection methods:

DB::statement(DB::raw('CREATE DATABASE <name>'));

为此,您可以使用辅助连接:

To do that you can use a secondary connection:

<?php
return array(

    'default' => 'mysql',

    'connections' => array(

        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'host1',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
        ),

        'store' => array(
            'driver'    => 'mysql',
            'host'      => 'host2',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
        ),
    ),
);

然后,您可以在应用程序引导期间更改辅助连接的数据库:

Then you can, during application bootstrap, change the database of the secondary connection:

DB::connection('store')->setDatabaseName($store);

Config::set('database.connections.store', $store);

并在查询中使用辅助连接:

And use the secondary connection in your queries:

$user = User::on('store')->find(1);

DB::connection('store')->select(...);

这篇关于在Laravel 4中即时创建新数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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