PHP Laravel 多数据库连接使用

gerardo · 2019-10-21 19:59:18

数据库配置

1、配置 .env 文件

DB_DB1_CONNECTION=db1
DB_DB1_HOST=127.0.0.1
DB_DB1_PORT=3306
DB_DB1_DATABASE=db1.codercto.com
DB_DB1_USERNAME=codercto
DB_DB1_PASSWORD=123456

DB_DB2_CONNECTION=db2
DB_DB2_HOST=127.0.0.1
DB_DB2_PORT=3306
DB_DB2_DATABASE=db2.codercto.com
DB_DB2_USERNAME=codercto
DB_DB2_PASSWORD=123456

2、配置 config/database.php 文件

'db1' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_DB1_HOST', '127.0.0.1'),
    'port' => env('DB_DB1_PORT', '3306'),
    'database' => env('DB_DB1_DATABASE', 'forge'),
    'username' => env('DB_DB1_USERNAME', 'forge'),
    'password' => env('DB_DB1_PASSWORD', ''),
    'unix_socket' => env('DB_DB1_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => null,
    'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
    ]) : [],
    ],
'db2' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_DB2_HOST', '127.0.0.1'),
    'port' => env('DB_DB2_PORT', '3306'),
    'database' => env('DB_DB2_DATABASE', 'forge'),
    'username' => env('DB_DB2_USERNAME', 'forge'),
    'password' => env('DB_DB2_PASSWORD', ''),
    'unix_socket' => env('DB_DB2_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => null,
    'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
    ]) : [],
],

使用

1、文件 /app/Models/Ask.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Ask extends Model
{
    protected $connection = 'db1';

    protected $table = 'codercto';
}

2、数据库事务

DB::connection('asklib')->transaction(function (){
    $data = [
        'title'=>'test',
    ];

    Ask::query()->insertGetId($data);
});

查看所有标签

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册