Doctrine 2 can't use nullable=false in manyToOne relation?

SymfonyDoctrineDoctrine Orm

Symfony Problem Overview


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;

}

Symfony Solutions


Solution 1 - Symfony

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!

Solution 2 - Symfony

Only

@ORM\JoinColumn(nullable=false)

is required

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongremoView Question on Stackoverflow
Solution 1 - SymfonySgoettschkesView Answer on Stackoverflow
Solution 2 - SymfonyMauroBView Answer on Stackoverflow