问题
I have a Laravel 5 project (on a CentOS 7 machine) that connects to an external MSSQL database.
I followed the setup outlined here using FreeTDS.
When I hit the page using a browser I get the error: SQLSTATE[HY000] Unable to connect: Adaptive Server is unavailable or does not exist (severity 9)
.
But when I use php artisan tinker
and do something like App\MyModel::get();
, it returns an Illuminate\Database\Eloquent\Collection
instance with the records/models just fine.
Anyone knows what's wrong with this?
UPDATE
My .env
looks like the following:
SQLSRV_DB_DRIVER=sqlsrv
SQLSRV_DB_HOST=host.ip.address
SQLSRV_DB_DATABASE=my_db
SQLSRV_DB_USERNAME=my_username
SQLSRV_DB_PASSWORD=my_password
And my config/database.php
looks like:
'sqlsrv' => [
'driver' => env('SQLSRV_DB_DRIVER'),
'host' => env('SQLSRV_DB_HOST'),
'database' => env('SQLSRV_DB_DATABASE'),
'username' => env('SQLSRV_DB_USERNAME'),
'password' => env('SQLSRV_DB_PASSWORD'),
'prefix' => '',
];
My model has a connection specified: protected $connection = 'sqlsrv';
I'm using FreeTDS with unixODBC.
回答1:
SELinux is blocking your outgoing connection to MSSQL.
The proper solution is to allow apache to make the connection:
setsebool -P httpd_can_network_connect_db 1
The -P
flag makes the rule persistent, otherwise the rule is lost after a reboot.
回答2:
It turns out it wasn't a Laravel problem but a SELinux problem. I disabled SELinux by following this guide then I was able to access my project in a browser.
I know this is not the best solution but it works for my purpose.
来源:https://stackoverflow.com/questions/29640092/laravel-sqlsrv-works-in-tinker-mode-but-not-in-browser