Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

Laravel 本地配置数据库读写分离, 使用读数据库时报错

'mysql' => [
            'driver' => 'mysql',
            'read' => [
                'host' => '127.0.0.1',
                'database' => 'laravels',
            ],
            'write' => [
                'host' => '127.0.0.1',
                'database' => 'laravel',
            ],
            'url' => env('DATABASE_URL'),
//            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
//            'database' => env('DB_DATABASE', 'laravel'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_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'),
            ]) : [],
        ],

配置文件进行配置好了 , 并且read的数据库也有数据
image
但是在调用方法进行查询的时候 报错

$a = DB::connection('read')->table('users')->get();

image
这是为啥?
谢谢!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

?? 这里的 connection 不是指读写分离的 read,而是指多个数据库连接,也就是这里。
图片.png
对应的就是下面的,connections 字段。
图片.png

你这里可以不写 connection('read') ,Laravel 内部会自动选择的。

如果你要手动使用 连接,可以使用

DB::connection('mysql::read')->table('users')->get();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...