在laravel中实现ORM模型使用第二个数据库设置

2020-09-03 11:55:02

DB类连接第二个数据库的方法

在laravel中如果使用DB类进行第二个数据库的链接我们只需要设置config/database.php中添加一个数据库设置,如:

'mysql_branch' => [ 'driver' => 'mysql', 'host' => '192.168.2.56', 'port' => '3306', 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', ], 

在链接的时候加上一个函数DB::connection(‘mysql_branch')->table(‘table')->get()`

这样就可以了

使用ORM时候连接第二个数据库

在model类中添加私有属性如下:

class Branch extends Model { //取消时间戳 public $timestamps = false; //链接外部数据库 protected $connection = 'mysql_branch'; } 

这样就可以了!

相关文章 大家在看