下面是如何在Laravel中使用Facade搜索表数据和分页。
DB::table('customers')->paginate(15);
但它可以只使用DB,
那么如何在Facade句子中使用几个DB?
我希望使用DB作为读取和写入DB的分区或单句直接访问。
感谢advenced。
答案 0 :(得分: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()
...