Tibo
Tibo

Reputation: 197

Symfony/Doctrine/PHP : How to get a persisted object without saving it in an array

To resume my problem :

In my model, a Contact is owned by a Company, so when I create the Contact, I need to do something like

$contact->setCompany($company);

Let's say I need to create a Company and a Contact object for each row from an Excel file. If I encounter a known Company, I do not want to create it again. If another Contact is in the same Company, I want to use the persisted Company. In order to do that, I'm doing the following :

$newCompanies = array();

foreach ($rows as $row) {
    $company = $this->entityManager()->getRepository(Company::class)->findOneBy(array("name" => $companyName))); // try to find an existing Company in the DB

    if (!isset($company) {
        if (!isset($newCompanies[$companyName])) {
            $company = new Company();
            $company->setName($companyName);

            $this->entityManager->persist($company);
            $newCompanies[$companyName] = $company;   // save the company in an array so we can use it later
        } else {
            $company = $newCompanies[$companyName];
        }
    }

    $contact = new Contact();
    $contact->setCompany($company);
    [...]
}

Problem is, I always reach a really big array, and I think the php memory limit is reached everytime for (let's say) 5000+ rows.

Is there a "cleaner" solution beside saving my objects in an array ? Without changing the memory_limit in php.ini ?

Thank you

Upvotes: 1

Views: 1070

Answers (1)

shvv
shvv

Reputation: 379

You can flush changes to DB and unset (reassign) $newCompanies array as proposed at documentation.

$batchSize = 20;
foreach ($rows as $i => $row) {
    // Payload
    if (($i % $batchSize) === 0) {
        $this->entityManager->flush();
        $this->entityManager->clear();
        $newCompanies = [];
    }
}

Upvotes: 1

Related Questions