一個簡單多庫配置

最閒的碼農發表於2018-11-02

在根目錄找到.env檔案,因為我的庫在同一ip下,所以我直接定義一個庫名

    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=test1
    DB_USERNAME=root
    DB_PASSWORD=1234
     #dbname2
    DB_DATABASE_1=test2

然後找到根目錄下config/databses.php

    'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'test1'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', '1234'),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => 'sys_',
        'strict' => true,
        'engine' => null,
    ],

    #dbname2
    'mysql_test2' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE_1', 'test2'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', '1234'),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => 'sys_',
        'strict' => true,
        'engine' => null,
    ],

然後我們們再建立個TaskModel進行測試
首先引用use Illuminate\Support\Facades\DB;

    #建立個show1方法 #dbname1
    public function show1()
       {
            $show = DB::table('users')->get();
            return show;
       }

    #然後建立個show2方法 dbname2
    public function show2()
       {
            $show = DB::connection('mysql_test2')->table('users')->get();
            return show;
       }

最後我們在controller例項化model

     $model=new Task(); //例項化model
     $data = $model -> show1(); //呼叫model層中方法

最後補充一下,我們結果集是物件:
我們可以通過->get()->map(function ($value) {return (array)$value;})->toArray();讓結果集變成陣列格式

相關文章