我有一个学说设置,我不能使用集合的许多方面。
使用的对象:User.php:
class User extends 'App'Entity
{
/**
* @Id @Column(type="integer")
* @GeneratedValue
*/
private $id;
/**
* @ManyToOne(targetEntity="Company", inversedBy="users")
*/
private $company;
public function getCompany()
{
return $this->company;
}
public function setCompany($company)
{
$this->company = $company;
}
}
Company.php:
class Company extends 'App'Entity
{
/**
* @Id @Column(type="integer", nullable=false)
* @GeneratedValue
*/
private $id;
/**
* @OneToMany(targetEntity="User", mappedBy="company")
*/
private $users;
public function __construct()
{
$this->users = new 'Doctrine'Common'Collections'ArrayCollection();
}
public function getUsers()
{
return $this->users;
}
}
当我创建的关系似乎是工作。没有错误。然后我尝试了以下操作:
$company = $this->em->getRepository('App'Entity'Company')->findOneByName("Walmart");
$user = $this->em->getRepository('App'Entity'User')->findOneByName("Niek");
$user->setCompany($company);
$company2 = $this->em->getRepository('App'Entity'Company')->findOneByName("Ford");
$user2 = $this->em->getRepository('App'Entity'User')->findOneByName("Henk");
$company2->getUsers()->add($user2);
$this->em->flush();
当我检查数据库中的第一个用户时,公司是设置的。关系就在那里。秒不会持续。当我这样做的时候:
print_r('Doctrine'Common'Util'Debug::dump($company->getUsers(),$doctrineDepth));
print_r('Doctrine'Common'Util'Debug::dump($company->getUsers2(),$doctrineDepth));
我得到两个空数组。
似乎数组没有连接。它只在onetmany或ManyToOne关系上表现得像这样。有一个很多很多,一个在同一个项目中工作完美
任何想法?
您仍然需要将关系的两端设置为一对多或多对一关系:
$company2 = $this->em->getRepository('App'Entity'Company')->findOneByName("Ford");
$user2 = $this->em->getRepository('App'Entity'User')->findOneByName("Henk");
$company2->getUsers()->add($user2);
$user2->setCompany($company2);
$this->em->flush();
多对多有效的原因是你不需要设置关系的两边