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;
}
EDIT: solved. please note that this is wrong (note double quotes):
@ORM\JoinColumn(name="package_id", referencedColumnName="id", nullable="false")
While this is correct:
@ORM\JoinColumn(name="package_id", referencedColumnName="id", nullable=false)
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!