dea*_*ase 1 php doctrine doctrine-orm
我试图从父实体中删除注释,我记得在我的上一个网站上这样做,但现在它不起作用..
我的实体 - 用户
namespace Application\Entities;
use Doctrine\ORM\Mapping AS ORM,
Doctrine\Common\Collections\ArrayCollection;
/**
* Loan
*
* @ORM\Table(name="users")
* @ORM\Entity
*/
class Users{
/**
* @var integer $id
*
* @ORM\Column(type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string $username
*
* @ORM\Column(type="string", length=45, nullable=false)
*/
private $username;
/**
* @var ArrayCollection
*
* @ORM\OneToMany(targetEntity="Comments", mappedBy="author", cascade={"persist", "remove"})
*/
private $comments;
public function getComments(){
return $this->comments;
}
Run Code Online (Sandbox Code Playgroud)
和我的评论表:
namespace Application\Entities;
use Doctrine\ORM\Mapping AS ORM,
Doctrine\Common\Collections\ArrayCollection;
/**
* Loan
*
* @ORM\Table(name="comments")
* @ORM\Entity
*/
class Comments{
/**
* @var integer $id
*
* @ORM\Column(type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var integer $user_id
*
* @ORM\Column(type="integer", length=15, nullable=false)
*/
private $user_id
/**
* @var Loan
*
* @ORM\ManyToOne(targetEntity="Users", inversedBy="comments",cascade={"persist"})
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
* })
*/
private $author;
Run Code Online (Sandbox Code Playgroud)
这很好,它可以工作,我在用户存储库中获得所有称为注释的集合.
现在,我通常在需要删除时执行此操作:
$commentToDelete = $this->em->getRepository('Entities\Comments')->findOneById(375);
$userResults = $this->em->getRepository('Entities\Users')->findOneById(23);
$userResults->getComments()->removeElement($commentToDelete);
$this->em->flush();
Run Code Online (Sandbox Code Playgroud)
什么都没有删除,也没有抛出异常告诉我它没有.
我的教义也刷了它,检查了数据库,它仍然在那里..
更新:
直接在我删除元素后,我循环通过用户id = 23数据集,并且id375的注释数据不在那里......所以它从集合中删除了它而不是从数据库中删除它,我认为$em->flush()应该这样做?
请指教
谢谢
你需要使用
$em->remove($commentToDelete);
$em->flush();
Run Code Online (Sandbox Code Playgroud)
因为映射保留在注释中,所以您需要删除此实体以在刷新之前删除引用,这将将状态保存到db.