我想独立于作为主数据库的MYSQL连接到要用作参考的SQLserver
为此,请设置
.env
#mysql
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=hogedb
DB_USERNAME=hoge
DB_PASSWORD=password
#SQLserver
DB_CONNECTION=sqlsrv
DB_HOST=localhost
DB_DATABASE=databasename
DB_USERNAME=username
DB_PASSWORD=password
用户
protected $connection = 'sqlsrv';
我遇到错误
找不到驱动程序(SQL:从[用户]中选择*,其中[用户]。[deleted_at]为空)
答案 0 :(得分:6)
.env :
#mysql
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=hogedb
DB_USERNAME=hoge
DB_PASSWORD=password
#SQLserver
DB_SQL_HOST=localhost
DB_SQL_DATABASE=databasename
DB_SQL_USERNAME=username
DB_SQL_PASSWORD=password
还有config/database.php
:
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_SQL_HOST', 'localhost'),
'database' => env('DB_SQL_DATABASE', ''),
'username' => env('DB_SQL_USERNAME', ''),
'password' => env('DB_SQL_PASSWORD', ''),
'prefix' => '',
],
],
然后在用户中使用-protected $connection = "sqlsrv";
最后运行php artisan config:cache
。
答案 1 :(得分:1)
您已经配置了config/database.php
文件吗?
尝试像这样配置它
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'database_1'), //forge
'username' => env('DB_USERNAME', 'root'), // forge
'password' => env('DB_PASSWORD', ''),
.......
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST_SQLSRV', '127.0.0.1'), // Notice that we change the default so that it'll refer to another variable which will be DB_HOST_SQLSRV in the .env file
'port' => env('DB_PORT_SQLSRV', '1433'),
'database' => env('DB_DATABASE2_SQLSRV', 'database_2'),
'username' => env('DB_USERNAME', 'root'), // Remains as is if you won't change the username and password, change it if you need to
'password' => env('DB_PASSWORD', ''),
.......
],
在您的.env文件中,它应该看起来像这样
// Mysql
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=hogedb
DB_USERNAME=hoge
DB_PASSWORD=password
// SQL Server
DB_CONNECTION=sqlsrv // We call in the 'sqlsrv' that we configured in database.php
DB_HOST_SQLSRV=localhost
DB_PORT_SQLSRV=1433 // DON'T FORGET THIS, IT'S VERY IMPORTANT!
DB_DATABASE2_SQLSRV=databasename // We change 'DB_Database' to 'DB_Database2'
DB_USERNAME=root // We may not add this to the second one unless you configured for another username & password in database.php
DB_PASSWORD=
因此,基本上,您在database.php中配置的内容将从.env
中获取数据,如果您注意到其中包含 env env('DB_PORT_SQLSRV', '1433')
在配置文件夹中进行更改后,别忘了运行php artisan config:cache