I’m having a hard time figuring out how to properly use Doctrine 2 with zend framework. I’m reading the docs and basing what I’ve done so far on that and the zendcasts. The problems actually start when I try to do relational stuff with my db, since I’m not so sure how to use doctrine collections. In my test case, I have an User entity:
class User
{
/**
* @var integer
* @Column (name="id", type="integer", nullable=false)
* @Id
* @GenerateValue(strategy="IDENTIY")
*
*/
private $id;
/**
* @Column(type="string",length=60,nullable=true)
* @var string
*/
private $email;
/**
*
* @param \Doctring\Common\Collections\Collection $property
* @OneToMany(targetEntity="Countries",mappedBy="user", cascade={"persist", "remove"})
*/
private $countries;
public function __get($property)
{
return $this->$property;
}
public function __set($property, $value)
{
$this->$property = $value;
}
}
Which is related to the countries entity:
class Countries {
/**
* @var integer
* @Column (name="id", type="integer", nullable=false)
* @Id
* @GenerateValue(strategy="IDENTIY")
*
*/
private $id;
/**
*
* @var string
* @Column(type="string")
*/
private $countryName;
/**
*
* @var User
* @ManyToOne(targetEntity="User")
* @JoinColumns({
* @JoinColumn(name="user_id", referencedColumnName="id")
* })
*/
private $user;
public function __get($property)
{
return $this->$property;
}
public function __set($property, $value)
{
$this->$property = $value;
}
}
Now I can assign the countries from the controller with something like this:
$p1 = new \Federico\Entity\Countries();
$p1->countryName = 'Argentina';
$p2 = new \Federico\Entity\Countries();
$p2->countryName = 'España';
$u = new \Federico\Entity\User();
$u->firstname = 'John';
$u->lastname = 'Doe';
$u->id = 1;
which would show me this object:
object(Federico\Entity\User)[109]
private 'id' => int 1
private 'email' => null
private 'countries' =>
array
0 =>
object(Federico\Entity\Countries)[107]
private 'id' => null
private 'countryName' => string 'Argentina' (length=9)
private 'user' => null
1 =>
object(Federico\Entity\Countries)[108]
private 'id' => null
private 'countryName' => string 'España' (length=7)
private 'user' => null
public 'firstname' => string 'John' (length=4)
public 'lastname' => string 'Doe' (length=3)
If you pay attention to this, you’ll see that the user property is set to null in the country objects. I don’t understand if this is supposed to happen like this or not. Also, since users will be allowed to choose the countries from a checkbox list, and they’ll be able to choose more than one country,…shouldn’t the countries somehow be stored in the Db?
I don’t see where you assign country to a user in your code. Anyway, you need to do two things:
Initialize
$countriesvariable as a newDoctrine\Common\Collections\ArrayCollectionin User constructor.Manually connect country with user: