简体   繁体   English

如何在Laravel中将另一个数据库与模型连接

[英]How to connect another database with model in laravel

I am able to connect with another database like this 我可以像这样连接另一个数据库

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

But this code is not working 但是这段代码不起作用

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

You need to set the $connection property of your model like so: 您需要像这样设置模型的$connection属性:

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

Add in database.php: 在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
]

Then use: 然后使用:

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

In your User.php model: 在您的User.php模型中:

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

Then use: 然后使用:

User::get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM