database - 创建一个双向的多对多关联,带有额外的学说字段

标签 database doctrine-orm many-to-many symfony

我使用 symfony 3 和 doctrine,这是我的问题:
我想制作由不同数量的配料组成的菜肴。

数据库看起来像这样:

[ Dish ] <===> [ IngredientDish ] <===> [ Ingredient ]
[------]       [----------------]       [------------]
[- name]       [- Dish          ]       [-name       ]
[      ]       [- Ingredient    ]       [            ]
[      ]       [- quantity      ]       [            ]
[------]       [----------------]       [------------]

这是我的代码:

Dish.php

/**
 * @ORM\Table(name="dish")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\DishRepository")
 */
class Dish
{

     /**
      * @ORM\OneToMany(targetEntity="AppBundle\Entity\IngredientDish",
      *         mappedBy="dish")
      */
     private $ingredientsDish;

     [...]

     public function addIngredientDish(IngredientDish $ingredient)
     {
         $this->ingredientsDish[] = $ingredient;

         return $this;
     }

     public function getIngredientsDish()
     {
         return $this->ingredientsDish;
     }

 }

成分.php

/**
 * @ORM\Table(name="ingredient")
 *    @ORM\Entity(repositoryClass="AppBundle\Repository\IngredientRepository")
 */
 class Ingredient
 {

     /**
      * @ORM\OneToMany(targetEntity="AppBundle\Entity\IngredientDish",
      *     mappedBy="ingredient")
      * @Assert\Type(type="AppBundle\Entity\IngredientDish")
      */
     private $ingredientsDish;

     [...]

     public function addIngredientDish(IngredientDish $ingredientDish)
     {
         $this->ingredientDish[] = $ingredientDish;

         return $this;
      }

     public function getingredientsDish()
     {
         return $this->ingredients;
     }

 }

IngredientDish.php

/**
 * @ORM\Table(name="ingredient_dish")
 *    @ORM\Entity(repositoryClass="AppBundle\Repository\IngredientDishRepository")
 */
class IngredientDish
{

    /**
     * @ORM\Column(name="quantity", type="smallint")
     * @Assert\NotBlank()
     * @Assert\Length(min=1)
     */
    private $quantity = 1;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Ingredient",
     *      inversedBy="ingredientsDish")
     * @Assert\Type(type="AppBundle\Entity\Ingredient")
     */
    private $ingredient;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Dish",
     *      inversedBy="ingredientsDish")
     * @ORM\JoinColumn()
     * @Assert\Type(type="AppBundle\Entity\Dish")
     */
    private $dish;

    public function __construct(Ingredient $ingredient, Dish $dish, $quantity = 1)
    {
        $this->setIngredient($ingredient);
        $this->setDish($dish);
        $this->setQuantity($quantity);
    }

    public function setQuantity($quantity)
    {
        $this->quantity = $quantity;

        return $this;
    }

    public function getQuantity()
    {
        return $this->quantity;
    }

    public function setIngredient(Ingredient $ingredient)
    {
        $this->ingredient = $ingredient;
        return $this;
    }

    public function getIngredient()
    {  
        return $this->ingredient;
    }

    public function setDish(Dish $dish)
    {
        $this->dish = $dish;
        return $this;
    }

    public function getDish()
    {
        return $this->dish;
    }

}

我的测试代码

$em = $this->getDoctrine()->getManager();

//Get an apple pie
$dish = $em->getRepository('AppBundle:Dish')->find(6);

//Get an apple
$ingredient = $em->getRepository('AppBundle:Ingredient')->find(11);

$quantityApple = 5;

$ingredientDish = new IngredientDish($ingredient, $dish, $quantityApple);

$ingredient->addIngredientDish($ingredientDish);

$dish->addIngredientDish($ingredientDish);

$em->persist($ingredientDish);
$em->persist($dish);
$em->flush();

执行后,我有一个有趣的条目:

mysql> select * from ingredient_dish;
+----+---------------+----------+---------+
| id | ingredient_id | quantity | dish_id |
+----+---------------+----------+---------+
| 1  |            11 |        5 |       6 |
+----+---------------+----------+---------+

但是之后,如果我尝试拿到我的菜:

$dish = $em->getRepository('AppBundle:Dish')->find(6);
dump($dish->getIngredientsDish());

它没有成分:

PersistentCollection {#1180 ▼
    -snapshot: []
    -owner: Dish {#1146 ▶}
    -association: array:15 [ …15]
    -em: EntityManager {#1075 …11}
    -backRefFieldName: "dish"
    -typeClass: ClassMetadata {#1157 …}
    -isDirty: false
    #collection: ArrayCollection {#1181 ▼
        -elements: [] <<<<<<<<<<<<<<<<<<<<< EMPTY
    }
    #initialized: false
}

我的测试代码执行后数据库不为空,所以我认为是getter出错了。 你能帮我吗,你看到什么东西是假的吗?

感谢您的帮助! :)

最佳答案

我认为一切都很好,但你被延迟加载误导了,这显然比你想象的要聪明。 ;-)

当你这样做的时候

$dish->getIngredientsDish();

您收到 PersistentCollection,它扩展了 AbstractLazyCollection

但该集合仍未从 DB(!) 中提取

仔细查看您的 var_dump 结果

PersistentCollection {#1180 ▼
    -snapshot: []
    -owner: Dish {#1146 ▶}
    -association: array:15 [ …15]
    -em: EntityManager {#1075 …11}
    -backRefFieldName: "dish"
    -typeClass: ClassMetadata {#1157 …}
    -isDirty: false
    #collection: ArrayCollection {#1181 ▼
        -elements: [] <<<<<<<<<<<<<<<<<<<<< EMPTY //<= yeah empty, but...
    }
    #initialized: false // <= it's still not initialized!
}

如您所见,initialized 属性表示集合仍未初始化(未从 DB 获取)。

只是尝试使用它。它将在第一次使用时获取集合。

关于database - 创建一个双向的多对多关联,带有额外的学说字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39379829/

相关文章:

sql - 带有(不正确的?)索引的缓慢 PostgreSQL 查询

php - Symfony2 的 Doctrine 不会为我创建一对多结构

php - Laravel 5.5 更新多对多关系模型的复选框

mysql - 将表从一对多转换为多对多 MYSQL

database - 数据压缩定义

sql-server - SQL数据库学生时间表系统

php - Doctrine2 复杂的统计查询

forms - Sonata 管理员不保存多对多字段

database - 什么时候 table 太多?

php - Symfony2/Doctrine2 : Don't drop fulltext index on schema:update