I building Twitter clone app use Laravel5.4 and While referring to this
now i want seeding database with test data
in my terminal input php artisan db:seed --class=TweetsTableSeeder got error
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)
I read the error and tried to understand, but I had no good results. I'm looking at the official document but I can not understand much because beginner.
so please help me
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),
];
});
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2tD3ay8
via IFTTT
Aucun commentaire:
Enregistrer un commentaire