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

时间:2018-06-30 14:31:06

标签: symfony doctrine many-to-many

在我的Symfony代码中,我使用了Doctrine。在一个实体(AppBundle \ Entity \ Core \ User)中,我定义了一列foodTypes,该列与另一个实体(AppBundle \ Entity \ FoodRecording \ FoodType)关联。我已经定义了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会自动获取我需要的数据,但事实并非如此!

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

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检索数据?学说不够聪明吗?

1 个答案:

答案 0 :(得分:0)

此部分: print(converter(30, 12)) 属于$this->foodTypes = new \Doctrine\Common\Collections\ArrayCollection();方法,而不是getter。。您会看到,每次调用getter时,都将属性__construct重置为ArrayCollection的空实例