[英]Multi-database design application using Laravel 5.3 and Codeigniter
[英]Laravel 5.3 multi database
這可能是個常見問題,但我被困了 2 天 T_T
很簡單,
我在 config/database.php 中定義了 2 個 db 連接,如下所示:
'connections' => [ 'web' => [ 'driver' => 'mysql', 'host' => 'localhost', 'port' => '3306', 'database' => 'db_host1', 'username' => 'username1, 'password' => 'secret1', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], 'another' => [ 'driver' => 'mysql', 'host' => 'localhost', 'port' => '3306', 'database' => 'db_host2', 'username' => 'username2', 'password' => 'secret2', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], ]
明確而直接
php artisan make auth
修改遷移如下:
class CreateUsersTable extends Migration{ //bla.... public function up(){ Schema::connection('another')->create('users', function (Blueprint $table) { //bla } //bla } class CreatePasswordResetsTable extends Migration{ //bla.... public function up(){ Schema::connection('another')->create('password_resets', function (Blueprint $table) { //bla } //bla }
明確而直接
php artisan migrate - 甜蜜的,在正確的地方創建的數據庫
轉到 registercontroller.php 並修改 create 方法如下:
protected function create(array $data){ return User::create([ 'connection' => 'another', 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), ]); }
我還嘗試將連接放在app/User.php
,如下所示:
class User extends Authenticatable{ use Notifiable; protected $connection = 'another';
測試注冊用戶 - 填寫所有表單字段並提交
SQLSTATE[42S02]:未找到基表或視圖:1146 表“web.users”不存在(SQL:選擇計數(*)作為來自
users
聚合)
問題:為什么它仍然從“網絡”數據庫連接中查找,因為我已經告訴使用“另一個”數據庫連接 T_T ?
我在這里錯過了什么嗎?
我已經閱讀了一些文檔,例如: http : //fideloper.com/laravel-multiple-database-connections
但這對我沒有幫助...
如果有人可以在這里幫助我,不勝感激:)
干杯,
方法Schema::connection()
實際上並不存在。 執行此操作的理想方法是獲取連接的 schemabuilder:
DB::connection('another')->getSchemaBuilder()->create('users', function (Blueprint $table) {
// definitions
}
實際上有幾種方法可以做到這一點,我可以全部介紹,但這是最簡單的。
對於驗證部分。 盡管您在驗證部分將連接更改為另一個,但您仍在尋找 Web 連接用戶表,只需替換 RegisterController 中的以下代碼即可。
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:another.users',
'password' => 'required|min:6|confirmed',
]);
unique:another.users *這部分很重要,因為它說明要使用哪個連接以及驗證字段的表。
學分: laracast
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.