oneToOne 单向主义:获取映射对象

doctrine oneToOne unidirectional: get mapped object

我有三个简单实体:RecipeEntityIngredientEntityFoodEntity

据我正确理解学说关联 RecipeEntity 应该与 IngredientEntity 具有 双向 oneToMany 关系,因为一个食谱包含许多成分。 一种成分恰好包含一种食物,因此我假设成分与食物之间存在 单向 关联。 作为 ID,我使用第三方库使用 Uuid 而不是整数,这通常可以正常工作。

现在,我的 SQL 数据库中充满了指向食物成分的食谱。 当我调用食谱时,我可以检索成分。 在遍历配料时,我可以将食谱(双向关联)作为对象访问。

但是,当我想要访问食物时,我并没有像我预期的那样得到一个 FoodEntity 对象,而是只有食物的 id (由于使用了 uuid 库,它本身就是一个对象)。

为什么我得不到 FoodEntity 对象? 怎么了?

希望,我说清楚了! 感谢您的帮助。

干杯, LT.

这就是我所拥有的(为了更好的可读性而减少):

/**
 * Class RecipeEntity
 *
 * @ORM\Entity(repositoryClass="RecipeRepository")
 * @ORM\Table(name="recipe")
 *
 */
class RecipeEntity implements ArraySerializableInterface
{
    /**
     * @ORM\Column(name="id", type="uuid")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     */
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="IngredientEntity", mappedBy="recipe")
      */
    private $ingredients;

    public function __construct()
    {
        $this->ingredients = new ArrayCollection();
    }

    /**
     * @return Collection
     */
    public function getIngredients()
    {
        return $this->ingredients;
    }
}

/**
 * Class IngredientEntity
 *
 * @ORM\Entity
 * @ORM\Table(name="ingredient", indexes={@ORM\Index(name="recipe_id", columns={"recipe_id"}), @ORM\Index(name="food_id", columns={"food_id"})})
 */
class IngredientEntity implements ArraySerializableInterface
{
    /**
     * @ORM\Column(name="id", type="uuid")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     */
    private $id;

    /**
     * @ORM\Column(name="recipe_id", type="uuid")
     * @ORM\ManyToOne(targetEntity="RecipeEntity", inversedBy="ingredients")
     */
    private $recipe;

    /**
     * @ORM\Column(name="food_id", type="uuid")
     * @ORM\OneToOne(targetEntity="FoodEntity")
     */
    private $food;
}

/**
 * Class FoodEntity
 *
 * @ORM\Table(name="food", indexes={@ORM\Index(name="source_id", columns={"source_id"})})
 * @ORM\Entity(repositoryClass="LT\Model\Repository\FoodRepository")
 */
class FoodEntity implements ArraySerializableInterface
{
    /**
     * @ORM\Id
     * @ORM\Column(name="id", type="uuid")
     * @ORM\GeneratedValue(strategy="UUID")
     */
    private $id;
}

你犯的错误是你同时添加了 @Column 以及 @OneToOne(如果是食物)和 @ManyToOne(如果是食谱)。 属性 要么是 relation/association 要么是 field/column,不能两者都是。

您应该从实体定义的关联中删除 @Column 注释。

/**
 * Class IngredientEntity
 *
 * @ORM\Entity
 * @ORM\Table(name="ingredient", indexes={@ORM\Index(name="recipe_id", columns={"recipe_id"}), @ORM\Index(name="food_id", columns={"food_id"})})
 */
class IngredientEntity implements ArraySerializableInterface
{
    /**
     * @ORM\Column(name="id", type="uuid")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="RecipeEntity", inversedBy="ingredients")
     */
    private $recipe;

    /**
     * @ORM\OneToOne(targetEntity="FoodEntity")
     */
    private $food;
}