Laravel通过SQL文件播种

时间:2018-03-26 19:08:36

标签: php sql laravel seeding

我试图从播种机中的.sql文件读取数据,用一些数据填充3-4个表,而DatabaseSeeder.php看起来像这样

TypeError: unsupported operand type(s) for /: 'Counter' and 'int'

所有其他播种机执行,实际上,当尝试在SqlSeeder.php中抛出异常时,我能够停止播种。但是,SqlSeeder.php不会通过public function run() { $this->call([ UsersTableSeeder::class, // Bunch of seeders using Eloquent SqlSeeder::class ]); } 为数据库播种,似乎它被绕过了。我总是需要在php artisan migrate:fresh --seed之后运行,以便使它成为数据库的种子。 SqlSeeder.php看起来像这样

php artisan db:seed --class SqlSeeder

为什么?

3 个答案:

答案 0 :(得分:1)

我通过删除我试图通过public void processChange(int state) { this.state = state; notifyAllObservers(); 执行的.sql文件中的事务来解决自己的问题。奇怪的是,执行DB::unprepared()时事务完全失败,但如果我稍后通过php artisan migrate:refresh --seed单独调用SqlSeeder,它们就会起作用。现在没有外键约束,并且InnoDB被选为引擎,只是为了确定,但仍然根据命令,事务仍然失败并起作用。

我想这一切都取决于php artisan db:seed --class SqlSeeder如何工作并在内部调用播种器类,但我不确定。

答案 1 :(得分:0)

检查sql文件中的播种数据是否正确。

例如,如果您使用外键category_id,则在使用此sql文件时,对categories.id posts表的引用将为空且没有任何错误:

INSERT INTO posts (title, category_id) VALUES ('test', 1);
INSERT INTO categories (title) VALUES ('category');

您应首先播种类别,然后才发布帖子。

答案 2 :(得分:0)

对于Laravel 5,您需要在主种子文件中做的只是:

\DB::unprepared(\File::get(base_path('path/to/your/sql/file.sql')));