0

Below is how to use Facade for search table data with pagination in Laravel.

DB::table('customers')->paginate(15);

but it can be use just a DB,

So how to use several DB in Facade sentence?

I wish to use DB as divide as read and write DB or direct access in single sentence.

Thank you in advenced.

4

1 回答 1

0

首先,您必须在以下位置为您的数据库指定配置 .env

DB_CONNECTION=mysql
DB_HOST=172.17.0.1
DB_DATABASE=my_database
DB_USERNAME=username
DB_PASSWORD=password

DB_SLAVE_HOST=172.17.0.1
DB_SLAVE_DATABASE=my_database_slave
DB_SLAVE_USERNAME=username2
DB_SLAVE_PASSWORD=password2

DB_MASTER_HOST=172.17.0.1
DB_MASTER_DATABASE=my_database
DB_MASTER_USERNAME=username
DB_MASTER_PASSWORD=password

project.dev/config/database.php

    'mysql_master' => [
        'driver'    => 'mysql',
        'host'      => env('DB_MASTER_HOST', 'localhost'),
        'port'      => env('DB_MASTER_PORT', '3306'),
        'database'  => env('DB_MASTER_DATABASE', 'forge'),
        'username'  => env('DB_MASTER_USERNAME', 'forge'),
        'password'  => env('DB_MASTER_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
        'engine'    => null,
    ],
    'mysql_slave'        => [
        'driver'    => 'mysql',
        'host'      => env('DB_SLAVE_HOST', 'localhost'),
        'database'  => env('DB_SLAVE_DATABASE', 'forge'),
        'username'  => env('DB_SLAVE_USERNAME', 'forge'),
        'password'  => env('DB_SLAVE_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

然后你可以使用setConnection这样的方法:

public function getIndex(Product $product)
{
    $this->products = $product->setConnection('mysql_slave')
        ->where('id' '>' 20)
        ->get()
...
于 2017-09-15T09:24:44.387 回答