I'm trying to associate quests with levels for my game. Each level contains one or many quests. Each quest is associated to one level.
When running my DB seeds, I get
1452 Cannot add or update a child row: a foreign key constraint fails (
clg_local
.quests
, CONSTRAINTquests_level_id_foreign
FOREIGN KEY (level_id
) REFERENCESlevels
(id
) ON DELETE CASCADE)
Migrations: this is one of my migrations for quests:
Schema::create('quests', function(Blueprint $table)
{
$table->increments('id');
$table->string('quest_name')->nullable();
$table->unsignedInteger('level_id')->nullable();
Then when all of my tables are created, I run this migration to specify my FK relationships:
Schema::table('quests', function(Blueprint $table)
{
$table->foreign('level_id')->references('id')->on('levels')->onDelete('cascade');
});
Where it's failing in the seeding: QuestsSeeder
foreach (
[
[
'quest_name' => 'Quest 1',
'level_id' => 1,
'reward_xp' => 200,
'reward_items' => null,
'reward_money' => 200,
...
] as $input
) {
$quest = Quest::create($input);
$quests[] = $quest;
}
return $quests;
If I comment out $table->foreign('level_id')->references('id')->on('levels')->onDelete('cascade');
, it works fine, but then can't retrieve the quests per level as such:
$quests = Level::findOrFail(1)->quests();
I assume this is because I'm not allowed to add level_id => 1
when seeding... so I commented that out and it works:
[
'quest_name' => 'Quest 1',
//'level_id' => 1,
'reward_xp' => 200,
'reward_items' => null,
'reward_money' => 200,
],
But then how can I associate that quest entry with a level? I need to add the level id to the quest entry.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire