Ale*_*lex 1 php mysql seeding laravel-5 laravel-5.4
我使用 Laravel5.4 构建 Twitter 克隆应用程序并参考此
现在我想要用测试数据播种数据库
在我的终端输入中php artisan db:seed --class=TweetsTableSeeder
出现错误
Integrity constraint violation: 1452 Cannot add
or update a child row: a foreign key constraint fails (`twitter`.
`tweets`, CONSTRAINT `tweets_user_id_foreign` FOREIGN KEY (`user_
id`) REFERENCES `users` (`id`) ON DELETE CASCADE)
Run Code Online (Sandbox Code Playgroud)
我阅读了错误并尝试理解,但没有得到好的结果。我正在看官方文档,但由于初学者,我不太明白。
所以请帮助我
2017_07_09_create_tweets_table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTweetsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tweets', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('body', 140);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tweets');
}
}
Run Code Online (Sandbox Code Playgroud)
推文.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tweet extends Model
{
protected $fillable = [
'user_id', 'body',
];
}
Run Code Online (Sandbox Code Playgroud)
推文TableSeeder
<?php
use App\Tweet;
use Illuminate\Database\Seeder;
class TweetsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
factory(Tweet::class, 10)->create([
'user_id' => 2
]);
}
}
Run Code Online (Sandbox Code Playgroud)
模型工厂.php
<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
static $password;
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => str_random(10),
];
});
$factory->define(App\Tweet::class, function (Faker\Generator $faker) {
return [
'body' => $faker->realText(140),
];
});
Run Code Online (Sandbox Code Playgroud)
完整性约束违规:1452 无法添加或更新子行:外键约束失败(
tweets, CONSTRAINTtweets_user_id_foreignFOREIGN KEY (user_ id) REFERENCESusers(id) ON DELETE CASCADE)
上述错误仅意味着您正在尝试seed在表中(插入)一个值tweets,但该值在父表中不可用users。
通俗地说,当两个表共享foreign key关系时,只有那些值可以插入到父表中已经存在的子表中,在您的情况下,您违反了上述规则。