mardi 31 juillet 2018

Laravel - two factories refer to each other

I have an existing database, what is not modifiable. My current job is to make factories.

In the present case I have two tables. One is the item table, and the other is the item_image table.

An item has many images, but the featured-image-id stored in the item.

Here is my two factories:

Item factory

$factory->define(Item::class, function (Faker $faker) {
   return [
    'title' => $faker->words(3, true)
    'user' => function () {
      return factory(User::class)->create()->id;
    },
    'featured_image' => function () {
      return factory(Image::class)->create()->id;
    },
  ];
});

ItemImage factory

$factory->define(Image::class, function (Faker $faker) {
  return [
    'item' => function () {
      return factory(Item::class)->create()->id;
    },
  ];
});

item.featured_image column:

  • FK -> item_image.id
  • Not NULL

item_image.item column:

  • FK -> item.id
  • Not NULL

For example, when I want to create an item, the item factory refers to the itemImage factory, which would create an item that would create an image. bla bla bla. It cause an infinity loop.

How should i rewrite these factories?

Thanks for the help.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2v2jnyC
via IFTTT

Aucun commentaire:

Enregistrer un commentaire