如何将另一个数据库与 laravel 中的模型连接

How to connect another database with model in laravel

我可以像这样连接到另一个数据库

DB::connection('connection_2')->table("users")->get();

但是这段代码不起作用

User::connection('connection_2')->get();

加入database.php:

'main' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', 'localhost'),
    'database' => env('DB_MAIN', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix' => '',
    'strict' => false
],
'admin' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', 'localhost'),
    'database' => env('DB_ADMIN', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix' => '',
    'strict' => false
]

然后使用:

DB::connection('main')->table("users")->get();
DB::connection('admin')->table("users")->get();

在您的 User.php 模型中:

class User extends Model
{
    protected $connection = 'main';
    protected $table = 'users';
    protected $fillable = [
       'id','name'
    ];
}

然后使用:

User::get();

您需要像这样设置模型的 $connection 属性:

class MyModel extends Eloquent {
    protected $connection = 'connection_2';
}