第二个数据库中的Laravel播种表

Kla*_*aaz 0 mysql laravel laravel-5 artisan artisan-migrate

connection('mysql2')是我的(工作)第二个数据库连接.

当我首先迁移时,连接('mysql2')按预期工作,就会创建表.

Schema::connection('mysql2')->create('brands', function(Blueprint $table)
{
    //...
});
Run Code Online (Sandbox Code Playgroud)

但是当我尝试在第二个数据库中播种表时:

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Brands;

class DatabaseSeeder extends Seeder
{
    /**
    * Run the database seeds.
    *
    * @return void
    */
    public function run()
    {
        Model::unguard();
        $this->call('BrandsTableSeeder');
        $this->command->info("Brands table seeded.");
    }
}

class BrandsTableSeeder extends Seeder
{

    public function run()
    {
        DB::connection('mysql2')->table('brands')->delete();
        Brands::connection('mysql2')->create(['brand' => 'test']);
    }
}
Run Code Online (Sandbox Code Playgroud)

我有:

[BadMethodCallException]
Call to undefined method Illuminate\Database\Query\Builder::connection()
Run Code Online (Sandbox Code Playgroud)

Ana*_*tel 5

您的代码问题是您使用Connection()了Eloquent(而不是DB)的方法,Eloquent没有connection()方法.

您可以使用on()带模型的方法(Eloquent)来指定连接

$user = User::on('mysql2')->create(['brand' => 'test']);
Run Code Online (Sandbox Code Playgroud)

参考http://laravel.com/docs/4.2/eloquent#basic-usage

要么

而不是on('mysql2')到处写

你可以在模型中编写以下代码

protected $connection = 'mysql2'; 
Run Code Online (Sandbox Code Playgroud)

现在种子写成了

class BrandsTableSeeder extends Seeder
{
    public function run()
    {
        Brands::truncate();
        Brands::create(['brand' => 'test']);
    }
}
Run Code Online (Sandbox Code Playgroud)