国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > PHP > 正文

Laravel框架實現(xiàn)多數(shù)據(jù)庫連接操作詳解

2024-05-05 00:10:19
字體:
供稿:網(wǎng)友

本文實例講述了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è)計有所幫助。


注:相關(guān)教程知識閱讀請移步到PHP教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 襄城县| 通榆县| 寻乌县| 武邑县| 太湖县| 禄劝| 兴文县| 浙江省| 内江市| 靖边县| 德钦县| 台东市| 旅游| 策勒县| 廉江市| 正蓝旗| 莎车县| 海兴县| 吉首市| 湟中县| 卢氏县| 新田县| 内江市| 乌恰县| 阿拉尔市| 双柏县| 方山县| 闸北区| 永新县| 惠安县| 肇东市| 高陵县| 墨玉县| 饶平县| 徐水县| 沂水县| 海安县| 莱阳市| 信阳市| 奉节县| 墨江|