How can I use multiple connections in laravel models?

2

Guiding me on this answer , I try to make multiple connections in the following way:

'connections' => [

    'pgsql' => [
        'driver' => 'pgsql',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '5432'),
        'database' => env('DB_DATABASE', 'sistematpm'),
        'username' => env('DB_USERNAME', 'postgres'),
        'password' => env('DB_PASSWORD', 'root'),
        'charset' => 'utf8',
        'prefix' => '',
        'schema' => 'public',
        'sslmode' => 'prefer',
    ],

    'datos' => [
        'driver' => 'pgsql',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '5432'),
        'database' => env('DB_DATABASE', 'sistematpm'),
        'username' => env('DB_USERNAME', 'postgres'),
        'password' => env('DB_PASSWORD', 'root'),
        'charset' => 'utf8',
        'prefix' => '',
        'schema' => 'datos',
        'sslmode' => 'prefer',
    ],

],

The connection I try it in the following way and it serves me perfectly.

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

All right up there, but my system has many drivers already created, it will be a bit tedious to indicate to each one what connection it makes reference to. Could you only edit the models to indicate where the table is?

    
asked by Pablo Contreras 18.10.2017 в 06:55
source

1 answer

2

Yes, in the same answer they refer to how to handle a different connection to the default in a model, changing the value of the property $ connection:

<?php

class SomeModel extends Eloquent {

    protected $connection = 'mysql2';

}

The following example is from the documentation:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
    /**
     * The connection name for the model.
     *
     * @var string
     */
    protected $connection = 'connection-name';
}

In this order of ideas, the value of the property is changed to 'data'.

link

    
answered by 18.10.2017 / 13:41
source