Search code examples
phpsymfonydatetimedoctrinesymfony4

Persisting doctrine results with different values


I have some complex thing that I want to accomplish with one method.

In my Symfony project I am checking if the current datetime field is X days into the past. I am persisting boolean field to true on every table row where it is. So createdDate is less-than X days.

This part works as it should.

What I am trying to do is to the method goes both ways.

I want it also that if createdDate is greater-than X days. Also, to persist boolean field to false on every table row where it is.

My code:

    $date = new \DateTime();
    $date->modify('-7 days');

    $users = $this->userRepo->createQueryBuilder('u')
        ->where('u.createdDate < :date')
        ->setParameter(':date', $date)
        ->getQuery()
        ->getResult();

    foreach ($users as $user) {
        $user->setExceeded(true);

        $this->entityManager->persist($user);
        $this->entityManager->flush();
    }

    return $users;

Is there any possible way to do it and not in a separate method?

Like:

if() {

  ->andWhere('u.createdDate > :date')

   $user->setExceeded(false);
 }

Solution

  • $date = new \DateTime();
    $date->modify('-7 days');
    $users = $this->userRepo->findAll();
    
    foreach ($users as $user) {
        $user->setExceeded($user->getCreatedDate() < $date);
    }
    $this->entityManager->flush();
    
    return $users;