The classes can be created like my example below.
I based this on @rafix ‘s answer, but there were some problems.
Also, you don’t have to name your classes in the singular like @rafix indicated, you can name them however you want. But, it’s much better practive to do it that way and make your code much easier to read and support.
For example: If you have a class called “Country”, then you know a country has “cities”, and each one of those “cities” is a “City”. So the class refers to the individual object.
Here is the changes I suggest:
class Country
{
/**
* @ORM\Column(name="country_id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $country_id;
/**
* @ORM\Column(name="flag", type="string", length=100, nullable=true)
*/
private $flag;
/**
* @ORM\OneToMany(targetEntity="Region", mappedBy="country")
*/
private $regions = null;
public function __construct() {
$this->regions = new ArrayCollection();
}
}
class Region
{
/**
* @ORM\Column(name="region_id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $region_id;
/**
* @ORM\Column(name="name", type="string", length=100)
*/
private $name;
/**
* @ORM\ManyToOne(targetEntity="Country", inversedBy="regions")
* @ORM\JoinColumn(name="region_country_id", referencedColumnName="country_id")
*/
private $country;
/**
* @ORM\OneToMany(targetEntity="City", mappedBy="region")
*/
private $cities = null;
public function __construct() {
$this->cities = new ArrayCollection();
}
}
class City
{
/**
* @ORM\Column(name="city_id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $city_id;
/**
* @ORM\ManyToOne(targetEntity="Region", inversedBy="cities")
* @ORM\JoinColumn(name="region_id", referencedColumnName="region_id")
*/
private $region;
/**
* @ORM\Column(name="name", type="string", length=100)
*/
private $name;
}
Notice, I renamed each of the “id” s in each of the classes so you would know that it is the ID for that particular Entity. For example: The Country class has a “country_id”.
Also, since for example, the Country class has “regions”, you need to declare the array as “null”. Make sure you have the proper addRegion
to add regions to the array when you finish your code.
solved Doctrine Entities Relations confusing