首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >原理多对多关系:无法从数据库中自动获取数据

原理多对多关系:无法从数据库中自动获取数据
EN

Stack Overflow用户
提问于 2018-06-30 22:31:06
回答 1查看 33关注 0票数 0

在Symfony代码中,我使用了Doctrine。在一个实体( AppBundle\ Entity \Core\User )中,我定义了一个列foodTypes,它与另一个实体(AppBundle\ Entity \FoodRecording)相关联。我定义了User和FoodType之间的多对多关系,使用一个链接表foodrecording_user连接User.username和FoodType.foodtype_code。代码如下所示。

代码语言:javascript
复制
// 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;
}

然而,由于我想要直接获得某个用户的所有食物类型,所以使用

代码语言:javascript
复制
$userFoodTypes = $this->get('security.token_storage')->getToken()->getUser()->getFoodTypes();

然后我得到了

代码语言:javascript
复制
$userFoodTypes =====> array[]

我原以为创建了M-M关系后,Doctrine会自动获取我需要的数据,但事实并非如此!

因此,我必须编写自己的代码来从DB /表中检索数据,如下所示:

代码语言:javascript
复制
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还不够聪明吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-01 08:05:34

这部分:$this->foodTypes = new \Doctrine\Common\Collections\ArrayCollection();属于__construct方法,而不是getter。如下所示,每次调用getter时,都会将属性foodTypes重置为ArrayCollection的空实例

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51115837

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档