![](/img/trans.png)
[英]Doctrine 2: How to remove the relation as well as the entity in a many-to-many association
[英]how to remove a unidirectional many to many association with Doctrine 2
我在Badge和Request之間有一個單向的多對多關聯,如下所示:
徽章:
<?php
namespace Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Device
*
* @ORM\Table(name="badges")
* @ORM\Entity
*/
class Badges
{
/**
* Unidirectional - Many users have Many favorite comments (OWNING SIDE)
*
* @var \Doctrine\Common\Collections\Collection
*
* @ORM\ManyToMany(targetEntity="Entity\Request", cascade={"persist"})
*/
private $invite;
}
因為這是一個簡單的單向關聯,所以對Request實體沒什么特別的
添加關聯就可以了。
但是,當刪除關聯時,我正在這樣做:
$em = $this->CI->doctrine->em;
//Get badges for new notifs
$badges = $user->getBadges();
if( $badges )
{
$invites = $badges->getInvite();
if ( $invites )
{
foreach ( $invites as $key => $invite )
{
$badges->removeInvite( $invite );
}
}
$em->persist( $badges );
$em->flush();
}
else
{
return false;
}
但是它不起作用,並且在我嘗試從徽章分離的每個邀請中都出現此錯誤消息:
遇到PHP錯誤嚴重程度:注意
消息:未定義的索引:000000005ede1b52000000009e09e897
檔名:ORM / UnitOfWork.php
行號:2739
遇到PHP錯誤嚴重程度:警告
消息:array_pop()期望參數1為數組,給定null
文件名:Persisters / ManyToManyPersister.php
行號:143
現在,如果我僅從“徽章”中刪除一個請求:
$invites = $badges->getInvite();
if ( $invites )
{
foreach ( $invites as $key => $invite )
{
if( !empty( $invite ) ) {
$badges->removeInvite( $invite );
$em->persist( $invite );
$em->persist( $badges );
break;
}
}
}
我得到:
<b>Fatal error</b>: Uncaught exception 'Doctrine\\ORM\\ORMInvalidArgumentException' with message 'A new entity was found through the relationship 'Entity\\Badges#invite' that was not configured to cascade persist operations for entity: Entity\\Request@000000007c08aa8800000000c42081b4. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'Entity\\Request#__toString()' to get a clue.' in /var/www/meetmyfriends-dev/application/libraries/Doctrine/ORM/ORMInvalidArgumentException.php:59
請注意,我已按照此錯誤消息中的說明保留了請求(Entity \\ Badges#invite是Entity \\ Request)
為什么會這樣呢? 我該怎么解決? 我只想從“徽章”中分離邀請以將其移除以關聯。
謝謝
編輯:這是Badges#removeInvite方法和Badges#addInvite方法的實現:
/**
* Add invite
*
* @param \Entity\Request $invite
* @return Badges
*/
public function addInvite(\Entity\Request $invite)
{
$this->invite[] = $invite;
return $this;
}
/**
* Remove invite
*
* @param \Entity\Request $invite
*/
public function removeInvite(\Entity\Request $invite)
{
$this->invite->removeElement($invite);
}
嘗試這個:
foreach ( $invites as $key => $invite )
{
if(!empty($invite)){
$badges->removeInvite( $invite );
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.