欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2019年07月12日 09:43:20   作者:wong_gilbert  
這篇文章主要介紹了Laravel框架實現(xiàn)多數(shù)據(jù)庫連接操作,結(jié)合實例形式詳細分析了Laravel框架連接2個數(shù)據(jù)庫的具體操作步驟與相關(guān)實現(xiàn)技巧,需要的朋友可以參考下

本文實例講述了Laravel框架實現(xiàn)多數(shù)據(jù)庫連接操作。分享給大家供大家參考,具體如下:

這篇文章介紹了在laravel中連接2個數(shù)據(jù)庫的方法

一、定義連接

進入到數(shù)據(jù)庫配置文件 app/config/database.php 中,你可以定義多個形式相同或不同的數(shù)據(jù)庫連接。例如,你想從2個 MYSQL 數(shù)據(jù)中抓取資料到你的程式中,你可以這樣定義:

<?php
return 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'  => '',
    ),
  ),
);

默認連接任然是mysql,除非指定其他連接,如mysql2,我們的連接都是mysql連接。

2、指定連接

現(xiàn)在我們來指定mysql2連接,怎么做呢:

Schema 數(shù)據(jù)庫遷移

Schema facade 可以創(chuàng)建任意連接?,F(xiàn)在只需要用 connection() 方法就可以在指定的數(shù)據(jù)庫中創(chuàng)建table

Schema::connection('mysql2')->create('some_table', function($table)
{
  $table->increments('id'):
});

如果不加connection() 方法,就是在默認的數(shù)據(jù)庫中創(chuàng)建table

查詢

和上面一樣,用connection()方法

$users = DB::connection('mysql2')->select(...);

Eloquent

在模型中指定連接數(shù)據(jù)庫方法,在模型中設(shè)置 $connection 變量

<?php
class SomeModel extends Eloquent {
  protected $connection = 'mysql2';
}

在控制器中用 setConnection 方法也可連接指定數(shù)據(jù)庫

<?php
class SomeController extends BaseController {
  public function someMethod()
  {
    $someModel = new SomeModel;
    $someModel->setConnection('mysql2');
    $something = $someModel->find(1);
    return $something;
  }
}

跨數(shù)據(jù)庫連接是可以的,但是也可能帶來一些問題,這取決于你的數(shù)據(jù)庫或者數(shù)據(jù)庫配置,所以要謹慎使用。

原文地址:http://fideloper.com/laravel-multiple-database-connections

更多關(guān)于Laravel相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Laravel框架入門與進階教程》、《php優(yōu)秀開發(fā)框架總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總

希望本文所述對大家基于Laravel框架的PHP程序設(shè)計有所幫助。

相關(guān)文章

最新評論