【问题标题】:Laravel seeding tables in second database第二个数据库中的 Laravel 播种表
【发布时间】:2015-05-27 14:57:17
【问题描述】:

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

当我第一次迁移时,connection('mysql2') 工作正常,表已创建。

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

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

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']);
    }
}

我明白了:

[BadMethodCallException]
Call to undefined method Illuminate\Database\Query\Builder::connection()

【问题讨论】:

    标签: mysql laravel laravel-5 laravel-artisan artisan-migrate


    【解决方案1】:

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

    你可以使用on()方法和model(Eloquent)来指定连接

    $user = User::on('mysql2')->create(['brand' => 'test']);
    

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

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

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

    protected $connection = 'mysql2'; 
    

    现在种子写成

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

    【讨论】:

    • 感谢您向我指出基本概念。我仍然有点卡在老式的编程方式中......
    猜你喜欢
    • 1970-01-01
    • 2015-09-25
    • 2016-02-10
    • 2018-09-06
    • 1970-01-01
    • 2018-05-20
    • 2017-05-03
    • 2017-11-27
    相关资源
    最近更新 更多