我可以连接其他数据库
DB::connection('connection_2')->table("users")->get();
但是这段代码无效
User::connection('connection_2')->get();
答案 0 :(得分:3)
您需要设置模型的$connection
属性,如下所示:
class MyModel extends Eloquent {
protected $connection = 'connection_2';
}
答案 1 :(得分:1)
添加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();