Populating a database in a Laravel migration file(在 Laravel 迁移文件中填充数据库)
问题描述
我刚刚学习 Laravel,并且有一个工作迁移文件创建一个用户表.作为迁移的一部分,我正在尝试填充用户记录:
I'm just learning Laravel, and have a working migration file creating a users table. I am trying to populate a user record as part of the migration:
public function up()
{
Schema::create('users', function($table){
$table->increments('id');
$table->string('email', 255);
$table->string('password', 64);
$table->boolean('verified');
$table->string('token', 255);
$table->timestamps();
DB::table('users')->insert(
array(
'email' => 'name@domain.com',
'verified' => true
)
);
});
}
但是运行 php artisan migrate
时出现以下错误:
But I'm getting the following error when running php artisan migrate
:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'vantage.users' doesn't exist
这显然是因为 Artisan 尚未创建表,但所有文档似乎都说有一种方法可以使用 Fluent Query 来填充数据作为迁移的一部分.
This is obviously because Artisan hasn't yet created the table, but all the documentation seems to say that there is a way of using Fluent Query to populate data as part of a migration.
有人知道怎么做吗?谢谢!
Anyone know how? Thanks!
推荐答案
不要把 DB::insert() 放在 Schema::create() 里面,因为 create 方法必须先完成建表可以插入东西.试试这个:
Don't put the DB::insert() inside of the Schema::create(), because the create method has to finish making the table before you can insert stuff. Try this instead:
public function up()
{
// Create the table
Schema::create('users', function($table){
$table->increments('id');
$table->string('email', 255);
$table->string('password', 64);
$table->boolean('verified');
$table->string('token', 255);
$table->timestamps();
});
// Insert some stuff
DB::table('users')->insert(
array(
'email' => 'name@domain.com',
'verified' => true
)
);
}
这篇关于在 Laravel 迁移文件中填充数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Laravel 迁移文件中填充数据库
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- Laravel 仓库 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01