我知道有很多像这样的问题,但我向你保证,我已经过去了6个小时寻找互联网如何才能解决这个问题,但没有成功......
我使用Symfony2控制器作为服务,因此我必须将我需要的所有内容发送到控制器的__construct
方法。
我正在尝试使用2个实体,其中一个是“用户”,另一个是“部门”(我附上下面的文件内容),我有每个实体的存储库。
在用户实体内我使用@ORM\ManyToOne
与@ORM\JoinColumn
,而在部门实体内我有@ORM\OneToMany
。
所以,当我尝试这样做时......
$department = $this->departmentRepository->find(1);
$users = $department->getUsers();
...我得到ArrayCollection()
,但是当我这样做时......
$user = $this->userRepository->find(1);
$department = $user->getDepartment();
...此方法返回“null”而不是Department()
我检查了MySQL表,我向你保证,“users”表中存储的记录有部门的ID。所以,我不明白为什么会这样......
这是用户实体配置,关于@ORM\ManyToOne
和@ORM\JoinColumn
:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Table(name="`users`", options={"collate"="utf8_unicode_ci"})
* @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
*/
class User
{
// Here there are other properties
/**
* @ORM\ManyToOne(targetEntity="Department", inversedBy="users")
* @ORM\JoinColumn(name="`department_id`", referencedColumnName="`id`", nullable=true)
*/
private $department;
// Here there are Getters and Setters
}
这是部门实体,关于@ORM \ OneToMany:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Table(name="`departments`", options={"collate"="utf8_unicode_ci"})
* @ORM\Entity(repositoryClass="AppBundle\Repository\DepartmentRepository")
*/
class Department
{
// Here there are other properties
/**
* @ORM\OneToMany(targetEntity="User", mappedBy="department")
*/
private $users;
// Here there are Getters and Setters, and the Constructor
}
这是UserController:
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\User;
use AppBundle\Repository\UserRepository;
// There are more "use", I have cleaned this source code
/**
* @Route(service="app.user.controller")
*/
class UserController
{
// There are more properties
/**
* @var UserRepository
*/
private $userRepository;
// There are a constructor with this:
public function __constructor(UserRepository $userRepository) { $this->userRepository = $userRepository; }
/**
* There is a method to list all users (it works) but does not load the departments
*/
public function listAction()
{
$users = $this->userRepository->findAll();
exit(var_dump($users[0]->getDepartment()));
return ['users' => $users];
}
}
有人可以帮助我吗?
谢谢伙伴们,