Closed
Description
/**
* Class Entity
*
* @Entity(repositoryClass="TestRepo")
* @Table(name="test_entity")
*/
class Entity
{
/**
* @var int
* @Id
* @Column(type="integer")
* @GeneratedValue
*/
protected $id;
/**
* @var string
* @Column(type="string")
*/
protected $label = '';
/**
* @var Collection|Friend[]
* @OneToMany(targetEntity="Friend", mappedBy="entity", cascade={"all"}, orphanRemoval=true)
*/
protected $friends;
public function __construct()
{
$this->friends = new ArrayCollection();
}
public function addFriend(Friend $friend)
{
$friend->setEntity($this);
$this->friends->add($friend);
return $this;
}
public function setLabel(string $label)
{
$this->label = $label;
return $this;
}
}
/**
* Class Entity
* @Entity
* @Table(name="test_entity_friend")
*/
class Friend
{
/**
* @var Entity
* @id
* @ManyToOne(targetEntity="Entity", inversedBy="friends")
*/
protected $entity;
/**
* @var string
* @id
* @Column(type="string", length=400)
*/
protected $name = '';
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @param string $name
* @return $this
*/
public function setName(string $name)
{
$this->name = $name;
return $this;
}
public function setEntity(Entity $entity)
{
$this->entity = $entity;
return $this;
}
}
Usage:
$entity = new Entity();
$entity->setLabel('labelll');
$friend = new Friend();
$friend->setName('name');
$entity->addFriend($friend);
$entityManager->persist($entity);
$entityManager->flush();
Throws ORM/ORMInvalidArgumentException.php:68 "The given entity of type '\TestDoctrine\Entity\Friend' (\TestDoctrine\Entity\Friend@00000000309854b5000000005dfe4c27) has no identity/no id values set. It cannot be added to the identity map".
Because $entity has null id.
Flush after creating new Entity() and before adding $friend to $entity resolve this problem, but it makes many duct tapes.
Doctrine 2.6. Prev version works fine.