如何在laravel中使用模型连接另一个数据库

时间:2016-07-19 12:58:09

标签: php laravel database-connection

我可以连接其他数据库

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

但是这段代码无效

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

2 个答案:

答案 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();