Laravel 4 - Connect to other database

后端 未结 6 2139
暖寄归人
暖寄归人 2020-12-08 01:25

I want to connect to another database sometimes.

I created a config.php with the database connection data.

But how can i tell laravel to connect to this data

相关标签:
6条回答
  • 2020-12-08 01:48

    Remember that Laravel 4 is actually a collection of components, and you can use these components solo.

    https://github.com/illuminate/database

    There is an example here that shows off how interacting with the Capsule class works:

    use Illuminate\Database\Capsule\Manager as Capsule;
    
    $capsule = new Capsule;
    
    $capsule->addConnection([
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'database',
        'username'  => 'root',
        'password'  => 'password',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ]);
    
    // Set the event dispatcher used by Eloquent models... (optional)
    use Illuminate\Events\Dispatcher;
    use Illuminate\Container\Container;
    $capsule->setEventDispatcher(new Dispatcher(new Container));
    
    // Set the cache manager instance used by connections... (optional)
    $capsule->setCacheManager(...);
    
    // Make this Capsule instance available globally via static methods... (optional)
    $capsule->setAsGlobal();
    
    // Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
    $capsule->bootEloquent();
    

    This is a bunch of bootstrapping that you'll need to run, so tuck it away somewhere in a function or method.

    But, its absolutely possible.

    0 讨论(0)
  • 2020-12-08 01:48

    Edit bootstrap/start.php file and add your machine name (open terminal: hostname).

    Add your machine to $env,

    $env = $app->detectEnvironment(array(
        'mymachine' => array('mymachine.local'),
    ));
    
    1. Create a new path at 'app/config/mymachine'
    2. Add a copy of database.php with new config params.
    0 讨论(0)
  • 2020-12-08 01:50

    I believe you want to implement some kind of logical sharding where databases would be dynamically created.

    In such scenario in laravel you can dynamically add a database config, like below

    $conn = array(
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'DATABASE',
        'username'  => 'USERNAME',
        'password'  => 'SOME_PASSWORD',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    );
    
    Config::set('database.connections.DB_CONFIG_NAME', $conn);
    

    Now to connect via eloquent

    MODEL::on('DB_CONFIG_NAME')->WHAT_EVER('1');
    

    Incase of Query Builder you can do

    $DB = DB::connection('DB_CONFIG_NAME');
    

    use $DB->select() for querying now.

    Hope this would help devs looking for a possible solution for this question

    0 讨论(0)
  • 2020-12-08 01:55

    There is a simpler solution. If you are using Larave 4 there is an option that worked for me. Recently they added $table variable that you can specify in your model. Refer to this link.

    class User extends Eloquent {
    
        protected $table = 'my_users';
    
    }
    

    If you are using MySQL, you can do the following:

    class User extends Eloquent {
    
        protected $table = 'mydbname.my_users';
    
    }
    

    If you are using SQL Server, you can do this:

    class User extends Eloquent {
    
        protected $table = 'mydatabase..my_users';
    
    }
    

    My Config file had DB1 specified but I created a model which wants to access DB2 in the same MySQL host. So this was a quick and dirty way to accomplish this.

    Now I don't fully leverage Eloquent ORM all the time so this "hack" may not work with Many to Many or one to Many Eloquent methods.

    One another idea I had but I didn't actually try was creating a stored procedure (routine) in DB1 and inside of that routine I can access DB2 tables by querying link this:

    SELECT * from db2.mytable where id = 1;
    
    0 讨论(0)
  • 2020-12-08 01:57

    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.

    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.

    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.

    See that variable on here on Github and the method which you can set to set the connection dynamically here.

    Edit The OP has made it clear that they do not wish to use the config/database.php file for config.

    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.

    0 讨论(0)
  • 2020-12-08 02:01

    To use a config file in another location, say src/config:

    use Config;
    
    
    $this->dbConfig = Config::get('appname::dbInfo.connections.test');
    $this->database = $this->dbConfig['database'];
    $this->username= $this->dbConfig['username'];
    $this->password= $this->dbConfig['password'];
    

    Where dbInfo is a simple php file in your app's src/config directory returning an array containing the element connections which is an array of database properties.

    You can tell Laravel to use an external config file using:

    Config::set("database.connections.test", $this->dbConfig);
    DB::connection("test");
    
    0 讨论(0)
提交回复
热议问题