Reputation: 25005
How do you control the order of fixture loading when two fixtures depend on each other to load?
My schema has a Book entity, an Author entity, and a BookAuthor entity. Books can have many authors, and BookAuthor is required because it has an additional field called 'main' indicating whether the author is the main author of the book.
In BookFixtures, I reference BookAuthorFixtures:
$book1->addBookAuthor($manager->merge($this->getReference('book-author-1')));
In BookAuthorFixtures, I reference BookFixtures:
$bookAuthor1->setBook($manager->merge($this->getReference('book-1')));
One of the fixtures must be loaded first, which means the fixture it references is an undefined index.
Is there a trick to solving this issue?
This question addresses almost the same issue, but the configuration is different and the issue went unresolved despite the accepted answer.
Upvotes: 0
Views: 1049
Reputation: 2899
I don't know exactly how did you set up your relationships, but I think that this is what you should do:
1) Load the Author fixtures (they should require any books to be created)
2) Load the Book Fixtures. While you are creating the fixtures, in your load() method, you can create the "BookAuthor" entity for each book, and the book entity should be configured to save the BookAuthor entities it holds when it's persisted. The property "book_authors" inside the book entity could be something similar to this:
/**
* @ORM\OneToMany(targetEntity="your\bundle\Entity\BookAuthor",mappedBy="book", cascade={"persist", "remove"})
*/
protected $book_authors;
So in the Book fixtures, the code snippet that creates a book might be (don't forget to set any extra data, it's just a sample):
// [...]
$book = new Book();
$book->setTitle( 'xxx' )
// Set more data...
$book_author = new BookAuthor();
$book_author->setAuthor( $manager->merge($this->getReference('author-1')) );
$book_author->setBook( $book );
$book->addBookAuthor( $book_author );
$em->persist( $book );
// [...]
I hope it helped!
Upvotes: 1