我的Twitter構建克隆應用程序中使用Laravel5.4和While referring to thisLaravel種子:完整性約束違規:1452不能添加或更新子行:外鍵約束
現在我想播種數據庫測試數據失敗
在我端子輸入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)
我讀了錯誤,並試圖瞭解,但我沒有很好的效果。 我正在查看官方文檔,但因爲初學者而無法理解。
所以請幫我
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');
}
}
Tweet.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tweet extends Model
{
protected $fillable = [
'user_id', 'body',
];
}
TweetsTableSeeder
<?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
]);
}
}
ModelFactory.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),
];
});
謝謝你的回覆。感謝您提供易於理解的答案。爲了插入這個種子,我應該改變違反的內容嗎?如果可以,請告訴我要修復哪個部分? – Alex