Reputation: 59
I have two entities Categories and Criteria that are linked by ManyToMany relationship. It generated a new table named as criteria_categories in the database.
What i want to do is to use fixture to populate the entity Criteria
and the table criteria_categories
.
The categories table
has already data in the database.
So my problem is, how to get the data from categories
and insert them using fixtures into the criteria_categories table
?
My code is as follow:
Criteria
class Criteria
{
/**
* @ORM\ManyToMany(targetEntity="Categories", inversedBy="criteria", cascade={"persist"})
* @ORM\JoinTable(name="criteria_categories")
**/
private $categories;
}
Categories
class Categories
{
/**
* @ORM\ManyToMany(targetEntity="Criteria", mappedBy="categories")
**/
private $criteria;
}
DataFixtures
class LoadCriteria extends Fixture
{
public function load(ObjectManager $manager)
{
$criteria = array(
array(
'label' => 'Test1'
),
array(
'label' => 'Test2'
)
);
$cat = new Categories();
foreach ($criteria as $critere) {
$ctr = new Criteria();
$ctr->setCriteriaLabel($critere['label']);
$manager->persist($ctr);
}
$manager->flush();
}
}
So the real question is how to get the data from categories and use them here in this fixture to populate the table criteria_categories
?
Thanks in advance for your answer.
Upvotes: 1
Views: 1539
Reputation: 1016
In doctrine you can forget on criteria_categories
table. The class criteria
has a collection of categories
. Don't need to worry about additional tables used behind the scenes.
But to your question. To get all categories from the db, you have to define this fixture as a service and then inject an entity manager or your "wrapper" service.
class LoadCriteria extends Fixture
{
/**
* @var CategoriesRepository
*/
private $repository;
public function __construct(EntityManagerInterface $em)
{
$this->repository = $em->getRepository(Categories::class);
}
public function load(ObjectManager $manager)
{
$this->categories = $repository->findAll();
$criteria = array(
array(
'label' => 'Test1'
),
array(
'label' => 'Test2'
)
);
$cat = new Categories();
foreach ($criteria as $critere) {
$ctr = new Criteria();
$ctr->setCriteriaLabel($critere['label']);
$manager->persist($ctr);
}
$manager->flush();
}
}
If you don't use default service configuration, you have to define the fixture as service manually by.
#services.yml
App\DataFixtures\ORM\CriteriaFixture:
tags: [doctrine.fixture.orm]
Upvotes: 1