Home > Net >  How to set multiple names on one setName function?
How to set multiple names on one setName function?

Time:08-18

Hi i just started programming recently and I have doctrine fixture and foundry for my entities(Advertisement, Category($id, $name), User).

Since I couldn't figure out how to get my desired name out of foundry for Category i tried to write it myself in fixture(completely ignoring categoryFactory)using below code. But I'm getting only last of the array i've written(cpu). (Only ads with cpu category, no other categories were saved in database)

Basically what i had in my mind was to create Categories and make Advertisement for each of them.

class AppFixtures extends Fixture {

public function load(ObjectManager $manager): void
{
    $category = new Category();
    $names = array(
         'pc',
        'laptop',
         'cpu');
    foreach ($names as $name)
    {
        $nam = $category->setName($name);
        $manager->persist($nam);

        UserFactory::createMany(3);
        AdvertisementFactory::createMany(20,[
            'user'=> UserFactory::random(),
            'category'=>$nam
        ]);
    }
    $manager->flush();
}

}

please help. Thank u

CodePudding user response:

Try this:

public function load(ObjectManager $manager): void
{ 
    $names = array(
         'pc',
         'laptop',
         'cpu'
    );
    
   foreach ($names as $name)
   {
       $category = new Category();
       $category->setName($name); 
       
       $manager->persist($category);        
   }
   
   $manager->flush();
}

CodePudding user response:

I've finally solved it. @Anton M

    public function load(ObjectManager $manager): void
    {
    $names = array('pc', 'laptop', 'display','processor', 'cpu', 'gpu', 'ram', 'motherboard');

    foreach ($names as $name)
    {
        $category = new Category();
        $category->setName($name);
        $manager->persist($category);

        $advertisement = new Advertisement();
        UserFactory::createMany(10);
        AdvertisementFactory::createMany(20, function () use ($advertisement, $category) {
        return [
            'user' => UserFactory::random(),
            'category' => $category->addAdvertisement($advertisement)
        ];
        });

    }

    $manager->flush();

    }
  • Related