在Symfony代码中,我使用了Doctrine。在一个实体( AppBundle\ Entity \Core\User )中,我定义了一个列foodTypes,它与另一个实体(AppBundle\ Entity \FoodRecording)相关联。我定义了User和FoodType之间的多对多关系,使用一个链接表foodrecording_user连接User.username和FoodType.foodtype_code。代码如下所示。
// Entity\Core\User
namespace AppBundle\Entity\Core;
......
class User implements AdvancedUserInterface, \Serializable {
......
/**
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\FoodRecording\FoodType")
* @ORM\JoinTable(name="foodrecording_user",
* joinColumns={@ORM\JoinColumn(name="username", referencedColumnName="username", onDelete="CASCADE")},
* inverseJoinColumns={@ORM\JoinColumn(name="foodtype_code", referencedColumnName="code", onDelete="CASCADE")}
* )
*/
private $foodTypes;
public function getFoodTypes()
{
$this->foodTypes = new \Doctrine\Common\Collections\ArrayCollection();
return $this->foodTypes;
}
然而,由于我想要直接获得某个用户的所有食物类型,所以使用
$userFoodTypes = $this->get('security.token_storage')->getToken()->getUser()->getFoodTypes();
然后我得到了
$userFoodTypes =====> array[]
我原以为创建了M-M关系后,Doctrine会自动获取我需要的数据,但事实并非如此!
因此,我必须编写自己的代码来从DB /表中检索数据,如下所示:
public function fetchUserFoodTypes()
{
global $kernel;
$container = $kernel->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
$conn = $em->getConnection();
$sql = 'SELECT * FROM foodrecording_user where username = :username';
$stmt = $conn->prepare($sql);
$stmt->execute([
'username' => $this->getUsername(),
]);
$data = $stmt->fetchAll();
$res = [];
foreach ($data as $item) {
$foodtype = $em->getRepository('AppBundle\Entity\FoodRecording\FoodType')->findByCode($item['foodtype_code']);
$res[] = $foodtype;
}
return $res;
}
public function getFoodTypes()
{
$this->foodTypes = $this->fetchUserFoodTypes();
//$this->foodTypes = new \Doctrine\Common\Collections\ArrayCollection();
return $this->foodTypes;
}
只有这样,我才能获得与用户相关联的食物类型。
有人能向我解释一下,为什么我不能简单地使用M-M定义,让主义自动为我做所有的事情吗?为什么我要显式地编写自己的函数来从DB中检索数据?Doctrine还不够聪明吗?
发布于 2018-07-01 08:05:34
这部分:$this->foodTypes = new \Doctrine\Common\Collections\ArrayCollection();
属于__construct
方法,而不是getter。如下所示,每次调用getter时,都会将属性foodTypes
重置为ArrayCollection的空实例
https://stackoverflow.com/questions/51115837
复制相似问题