Doctrine2 OneToMany - ManyToOne returns empty collection with database ok
Have you tried defining your $delegation property like
/**
* @ORM\ManyToOne(targetEntity="Delegation", inversedBy="promotions")
* @ORM\JoinColumn(name="delegation_id", referencedColumnName="id")
*/
private $delegation;
See Doctrine2 Docs: Association Mapping->Many-To-One
Also there are a lot of typos in your code. For example
/**
* @ORM\OneToMany(targetEntity="Promotion", mappedBy="delegacion", cascade={"all"}, orphanRemoval=true)
*/
protected $promotions;
mappedBy="delegacion"
should be mappedBy="delegation"
.
Or
public function getDeleTacion()
{
return $this->deleTacion;
}
Should be
public function getDelegation()
{
return $this->delegation;
}
Edit
Okay, I created a minimalistic version for you that worked for me. You can built it up from there or watch for differences with your code:
Promotion.php
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Promotion
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Delegation", inversedBy="promotions", cascade={"persist"})
* @ORM\JoinColumn(name="delegation_id", referencedColumnName="id")
*/
public $delegation;
/**
* @ORM\ManyToOne(targetEntity="Product", inversedBy="promotions", cascade={"persist"})
* @ORM\JoinColumn(name="product_id", referencedColumnName="id")
*/
public $product;
}
Delegation.php
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Delegation
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="Promotion", mappedBy="delegation", cascade={"all"}, orphanRemoval=true)
*/
public $promotions;
public function __construct() {
$this->promotions = new \Doctrine\Common\Collections\ArrayCollection();
}
}
Product.php
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Product
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="Promotion", mappedBy="product", cascade={"all"}, orphanRemoval=true)
*/
public $promotions;
public function __construct() {
$this->promotions = new \Doctrine\Common\Collections\ArrayCollection();
}
}
If you now do something like
$delegation = new Delegation();
$product = new Product();
$promotion = new Promotion();
$promotion->delegation = $delegation;
$promotion->product = $product;
$em->persist($promotion);
$em->flush();
$products = $em->createQuery('select p from BundleName\Entity\Product p')->execute();
$delegations = $em->createQuery('select d from BundleName\Entity\Delegation d')->execute();
var_dump(count($products[0]->promotions), count($delegations[0]->promotions));
You should end up with
int(1)
int(1)
So the refrence is in fact saved and can be read. Phew. Good luck with that! :-)