本文實例講述了Laravel框架實現(xiàn)多數(shù)據(jù)庫連接操作。分享給大家供大家參考,具體如下:
這篇文章介紹了在laravel中連接2個數(shù)據(jù)庫的方法
一、定義連接
進(jìn)入到數(shù)據(jù)庫配置文件 app/config/database.php 中,你可以定義多個形式相同或不同的數(shù)據(jù)庫連接。例如,你想從2個 MYSQL 數(shù)據(jù)中抓取資料到你的程式中,你可以這樣定義:
<?phpreturn array( 'default' => 'mysql', 'connections' => array( # Our primary database connection 'mysql' => array( 'driver' => 'mysql', 'host' => 'host1', 'database' => 'database1', 'username' => 'user1', 'password' => 'pass1' 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ), # Our secondary database connection 'mysql2' => array( 'driver' => 'mysql', 'host' => 'host2', 'database' => 'database2', 'username' => 'user2', 'password' => 'pass2' 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ), ),);
默認(rèn)連接任然是mysql,除非指定其他連接,如mysql2,我們的連接都是mysql連接。
2、指定連接
現(xiàn)在我們來指定mysql2連接,怎么做呢:
Schema 數(shù)據(jù)庫遷移
用 Schema facade 可以創(chuàng)建任意連接。現(xiàn)在只需要用 connection() 方法就可以在指定的數(shù)據(jù)庫中創(chuàng)建table
Schema::connection('mysql2')->create('some_table', function($table){ $table->increments('id'):}); 如果不加connection() 方法,就是在默認(rèn)的數(shù)據(jù)庫中創(chuàng)建table
查詢
和上面一樣,用connection()方法
$users = DB::connection('mysql2')->select(...);Eloquent
在模型中指定連接數(shù)據(jù)庫方法,在模型中設(shè)置 $connection 變量
<?phpclass SomeModel extends Eloquent { protected $connection = 'mysql2';}在控制器中用 setConnection 方法也可連接指定數(shù)據(jù)庫
<?phpclass SomeController extends BaseController { public function someMethod() { $someModel = new SomeModel; $someModel->setConnection('mysql2'); $something = $someModel->find(1); return $something; }}跨數(shù)據(jù)庫連接是可以的,但是也可能帶來一些問題,這取決于你的數(shù)據(jù)庫或者數(shù)據(jù)庫配置,所以要謹(jǐn)慎使用。
原文地址:http://fideloper.com/laravel-multiple-database-connections
希望本文所述對大家基于Laravel框架的PHP程序設(shè)計有所幫助。
新聞熱點
疑難解答
圖片精選