gpt4 book ai didi

symfony - 原则 2 - 多对多关系 - 空集合

转载 作者:行者123 更新时间:2023-12-04 08:47:30 24 4
gpt4 key购买 nike

我在用户和组之间有多对多关系,但是当我想访问用户的所有组时,我得到的是空集合。

namespace LoginBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
* @ORM\Entity
* @ORM\Table(name="User")
*/
class User
{
/**
* @ORM\Column(type="integer", name="id")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $_iId;

/**
* @ORM\Column(type="string", name="login", length=45)
*/
private $_sLogin;

/**
* @ORM\ManyToMany(targetEntity="GroupBundle\Entity\Group", inversedBy="_aUser")
* @ORM\JoinTable(name="Group_x_User",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")}
* )
*/
private $_aGroup;

public function __construct() {
$this->_aGroup = new ArrayCollection();
}

/**
* Get iId
*
* @return integer
*/
public function getId()
{
return $this->_iId;
}

/**
* Set sLogin
*
* @param string $sLogin
*
* @return User
*/
public function setLogin($sLogin)
{
$this->_sLogin = $sLogin;

return $this;
}

/**
* Get sLogin
*
* @return string
*/
public function getLogin()
{
return $this->_sLogin;
}

public function getGroups()
{
return $this->_aGroup;
}

用户和组使用 Group_x_User 表来存储它们的关系。

namespace GroupBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
* @ORM\Entity
* @ORM\Table(name="Group")
*/
class Group
{
/**
* @ORM\Column(type="integer", name="id")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $_iId;

/**
* @ORM\Column(type="string", name="name", length=45)
*/
private $_sName;

/**
* @ORM\ManyToMany(targetEntity="LoginBundle\Entity\User", mappedBy="_aGroup")
*/
private $_aUser;

public function __construct() {
$this->_aUser = new ArrayCollection();
}

/**
* Get iId
*
* @return integer
*/
public function getId()
{
return $this->_iId;
}

/**
* Set sName
*
* @param string $sName
*
* @return Group
*/
public function setName($sName)
{
$this->_sName = $sName;

return $this;
}

/**
* Get sName
*
* @return string
*/
public function getName()
{
return $this->_sName;
}

public function getUsers()
{
return $this->_aUser;
}
}

我使用代码从数据库中恢复数据:

$oUser = $this->getDoctrine()
->getRepository('LoginBundle:User')
->find(2);
$aGroup = $oUser->getGroups();

不幸的是 $aGroup 集合包含 0 个元素的数组,而在数据库中是匹配的记录。我在映射中缺少什么?

最佳答案

User 类中缺少某些内容。您只需使用 ArrayCollection 声明 _aGroup。这还不够。您必须将数据存储到 ArrayCollection 中。

将其添加到 User 类中。

public class addGroups(\GroupBundle\Entity\Group $group)
{
$group->addUsers($this);
$this->_aGroup->add($group);
}

这是针对 Group 类的。

public class addUsers(\LoginBundle\Entity\User $user)
{
if (!$this->_aUser->contains($user)) {
$this->_aUser->add($user);
}
}

更多信息可以访问这个link .

关于symfony - 原则 2 - 多对多关系 - 空集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38970331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com