symfony3 Declaring Entities Declaring a Symfony Entity with annotations


Example

  • AppBundle/Entity/Person.php
<?php

namespace AppBundle\Entity;

use DoctrineORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity
 * @ORM\Table(name="persons")
 * @ORM\Entity(repositoryClass="AppBundle\Entity\PersonRepository")
 * @UniqueEntity("name")
 */
class Person
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", name="name", length=20, nullable=false)
     */
    protected $name;

    /**
     * @ORM\Column(type="integer", name="age", nullable=false)
     */
    protected $age;

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    public function getAge()
    {
        return $this->age;
    }

    public function setAge($age)
    {
        $this->age = $age;
        return $this;
    }
}
  • Generate the entity
php bin/console doctrine:generate:entities AppBundle/Person
  • To dump the SQL statements to the screen
php bin/console doctrine:schema:update --dump-sql
  • Create the table
php bin/console doctrine:schema:update --force

Or use the recommended way (assuming you already have doctrine-migrations-bundle installed in your project):

php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate