我有一个带有本地和远程数据库的Laravel项目。我在.env
中设置了这些内容。当尝试访问远程数据库时,Laravel正在尝试使用本地数据库,但我收到错误。疯狂的是,如果我在.env
文件中删除远程数据库的密码,它会抛出一个关于远程数据库拒绝访问的错误。
我读到如果辅助数据库出现错误,它将恢复为默认数据库,这看起来就像正在发生的事情。但是,我用Sequel Pro连接到远程数据库,所以我知道我的连接很好。这是.env
:
APP_ENV=local
APP_DEBUG=true
APP_KEY=JnsC2R88qLM6GTnivxLWPKs2ds2dfplI
SITE_URL=http://health.dev
DB_REMOTE_HOST=myhost.cc
DB_REMOTE_DATABASE=databasename
DB_REMOTE_USERNAME=username
DB_REMOTE_PASSWORD=password
DB_LOCAL_HOST=localhost
DB_LOCAL_DATABASE=health
DB_LOCAL_USERNAME=homestead
DB_LOCAL_PASSWORD=secret
我的database.php
:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_LOCAL_HOST', 'localhost'),
'database' => env('DB_LOCAL_DATABASE', 'forge'),
'username' => env('DB_LOCAL_USERNAME', 'forge'),
'password' => env('DB_LOCAL_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
'mysql_remote' => [
'driver' => 'mysql',
'host' => env('DB_REMOTE_HOST', ''),
'database' => env('DB_REMOTE_DATABASE', ''),
'username' => env('DB_REMOTE_USERNAME', ''),
'password' => env('DB_REMOTE_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
我的Center
型号:
<?php
namespace App;
use DB;
use Illuminate\Database\Eloquent\Model;
class Center extends Model
{
protected $table = 'Center';
private $center;
public function __construct()
{
$this->center = DB::connection('mysql_remote')->table($this->table);
}
}
答案 0 :(得分:2)
无需传入构造函数。您可以通过模型中的protected属性设置连接:
class Center extends Model
{
protected $table = 'Center';
protected $connection = 'mysql_remote';
}
答案 1 :(得分:0)
您还可以使用以下方法
class SomeController extends BaseController {
public function someMethod()
{
$someModel = new SomeModel;
$someModel->setConnection('mysql2');//main line
$something = $someModel->find(1);
return $something;
}
}