entityManager->createQueryBuilder() ->select('b') ->from(Bovine::class, 'b') ->where('b.buildingCase IS NOT NULL OR b.building IS NOT NULL') ->andWhere('NOT EXISTS (SELECT 1 FROM '.BovineMovement::class.' m WHERE m.bovine = b)') ->getQuery() ->getResult() ; $total = count($bovines); if (0 === $total) { $io->success('Aucun bovin à backfiller.'); return Command::SUCCESS; } $io->info(sprintf('%d bovin(s) à backfiller.', $total)); $now = new DateTimeImmutable(); $created = 0; $fallback = 0; foreach ($bovines as $i => $bovine) { $movement = new BovineMovement(); $movement->setBovine($bovine); if (null !== $bovine->getBuildingCase()) { $movement->setBuildingCase($bovine->getBuildingCase()); } else { $movement->setBuilding($bovine->getBuilding()); } $enteredAt = $bovine->getArrivalDate(); if (null === $enteredAt) { $enteredAt = $now; ++$fallback; } $movement->setEnteredAt($enteredAt); $this->entityManager->persist($movement); ++$created; if (0 === ($i + 1) % self::FLUSH_EVERY) { $this->entityManager->flush(); } } $this->entityManager->flush(); $io->success(sprintf('%d mouvement(s) créé(s).', $created)); if ($fallback > 0) { $io->warning(sprintf("%d bovin(s) sans date d'arrivée → enteredAt = maintenant.", $fallback)); } return Command::SUCCESS; } }