How can I seed a table with two foreign keys from the same table like messages:
Migration:
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->integer('to')->unsigned();
$table->integer('from')->unsigned();
$table->integer('parent_id')->unsigned()->nullable();
$table->text('body');
$table->boolean('status')->default(false);
$table->timestamps();
});
Schema::table('messages', function (Blueprint $table) {
$table->foreign('to')
->references('id')->on('users')
->onDelete('cascade');
$table->foreign('from')
->references('id')->on('users')
->onDelete('cascade');
$table->foreign('parent_id')
->references('id')->on('messages');
});
}
ModelFactory:
$factory->define(App\Message::class, function($faker) {
return [
'body' => $faker->text
'from' => //user id,
'to' => //user id,
'parent_id' => //message id
];
});
- How can i get user ids here?
- How do I get an existing row of message for the id?
Late to the party but I have another solution:
When creating your factory for whatever Model, the first few times, let the parent_id be 0. After a specified created entries in the DB, you can pass in the real fetched data which is already created.
I'm using this to self reference categories and subcategories.
Using this method you will have at least 1 entry without a parent if you set the
count($categories) <= 1
which is needed to add parent_id's to your DB. If it's absolutely needed to have all entries have a parent_id, it only takes a manual change of 1 column in your DB.