[英]doctrine oneToOne unidirectional: get mapped object
我有三個簡單的實體: RecipeEntity
、 IngredientEntity
和FoodEntity
。
正如我正確理解學說關聯, 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
(在食譜的情況下)。 屬性要么是關系/關聯,要么是字段/列,而不是兩者。
您應該從實體定義中的關聯中刪除@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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.