121

An User has one Package associated with it. Many users can refer to the same package. User cannot exists without a Package defined. User should own the relation. Relation is bidirectional, so a Package has zero or more users in it.

These requirements lead to ManyToOne relation for User and OneToMany relation of Package in Doctrine 2. However package_id in user table (that is foreign-key) allows null values. I've tried setting nullable=false but command:

 php app/console doctrine:generate:entities DL --path="src" --no-backup

Says that there is no attribute nullable for the relation ManyToOne. What i'm missing?

class User
{

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Package", inversedBy="users")
     */
    private $package;

}

class Package
{

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="User", mappedBy="package")
     */
    private $users;

}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
gremo
  • 47,186
  • 75
  • 257
  • 421

2 Answers2

218

Use the JoinColumn annotation on your ManyToOne relation:

/**
 * @ORM\ManyToOne(targetEntity="Package", inversedBy="users")
 * @ORM\JoinColumn(name="package_id", referencedColumnName="id", nullable=false)
 */
private $package;

The ManyToOne itself cannot be nullable, because it doesn't relate to a specific column. The JoinColumn on the other hand identifies the column in the database. Thus, you can use "normal" attributes like nullable or unique!

Sgoettschkes
  • 13,141
  • 5
  • 60
  • 78
  • Thanks, i've tried but unfortunately the column `package_id` is still flagged as Null - Yes, Default - NULL. Any help is much appreciated. – gremo Mar 12 '12 at 20:49
  • 6
    Nevermind, a double quote completly break the thing. That is `nullable="false"` is wrong! – gremo Mar 12 '12 at 20:51
  • Did you try deleting the database entirly and creating it new? I just had a look at my database (using the same JoinColumn annotation as mentioned above) and it's flagged as NotNull! – Sgoettschkes Mar 12 '12 at 20:51
  • 5
    Thanks for this, I'd been wondering why I couldn't make it `@ORM\Column(nullable=true)` to make my manytoone nullable! – Scott Flack Nov 25 '13 at 00:27
  • If you configured the right option and you still see your database column with the wrong value, remember to clear metadata cache for Entity Manager. On Symfony, you can use `console doctrine:cache:clear-metadata` command – Massimiliano Arione Sep 24 '19 at 11:19
3

Only @ORM\JoinColumn(nullable=false) is required

yAnTar
  • 4,269
  • 9
  • 47
  • 73
MauroB
  • 510
  • 4
  • 12