E
E
Eugene2021-01-19 16:54:15
symfony
Eugene, 2021-01-19 16:54:15

How to set default value for DOCTRINE ORM entity?

Hello

Can you tell me if it is possible to set an SQL statement as a default value using Doctrine ORM?

It is necessary that when creating the Operation entity in the number field, the result of executing the sql expression is saved - CONCAT('T', LPAD(nextval('number_id_seq')::text, 12, '0'))

Something like this:

/**
 * @ORM\Entity(repositoryClass=OperationRepository::class)
 * @ORM\HasLifecycleCallbacks()
 */
class Operation {
  /**
   * @ORM\PrePersist()
   */
  public function prePersist(): void {
    if (empty($this->number)){
      $this->number = new Expression("CONCAT('T', LPAD(nextval('number_id_seq')::text, 12, '0'))");
    }
    if (empty($this->createdAt)){
      $this->createdAt = new Expression('NOW()');
    }
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tukreb, 2021-01-19
@tukreb

It is possible, throughoptions={"default"="now()"}

/**
     * @ORM\Column(name="date", type="datetime_immutable", nullable=false, options={"default"="now()"})
     */
    private \DateTimeImmutable $date;

It definitely works with now(), I haven’t tested anything more complicated, but I don’t see any reason why it shouldn’t work. True, it’s not a fact who the doctrine will be able to correctly generate the migration, you may have to rule with your hands in the migration.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question