为了账号安全,请及时绑定邮箱和手机立即绑定

ManyToMany 与 Symfony 5 的关系:不保存

ManyToMany 与 Symfony 5 的关系:不保存

PHP
慕斯王 2023-10-15 15:15:38
对于我的项目,我创建了 2 个实体:配方和成分。它们是多对多关系。 mysql 架构我从控制台生成了所有内容(实体和 CRUD)。但是,我无法保存食谱的成分,“成分”字段不保存任何内容,只保存日期和名称。我尝试在我的实体中添加“cascade={”persist”}”,但它不起作用。预先感谢您的帮助 !成分.php<?phpnamespace App\Entity;use App\Repository\IngredientRepository;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;/** * @ORM\Entity(repositoryClass=IngredientRepository::class) */class Ingredient{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string", length=255)     */    private $name;    /**     * @ORM\ManyToMany(targetEntity=Recette::class, inversedBy="ingredients",cascade={"persist"})     */    private $recette;    public function __construct()    {        $this->recette = new ArrayCollection();    }    public function getId(): ?int    {        return $this->id;    }    public function getName(): ?string    {        return $this->name;    }    public function setName(string $name): self    {        $this->name = $name;        return $this;    }    /**     * @return Collection|Recette[]     */    public function getRecette(): Collection    {        return $this->recette;    }    public function addRecette(Recette $recette): self    {        if (!$this->recette->contains($recette)) {            $this->recette[] = $recette;        }        return $this;    }    public function removeRecette(Recette $recette): self    {        if ($this->recette->contains($recette)) {            $this->recette->removeElement($recette);        }        return $this;    }    public function __toString()    {        return $this->name;    }}
查看完整描述

2 回答

?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

在多对多关系中,单向删除/添加不起作用。对于这种多对多关系,您必须从两个实体调用删除/添加方法 $recette->addIngredient($ingredients); $Ingredients->addRecettes($recette);



查看完整回答
反对 回复 2023-10-15
?
皈依舞

TA贡献1851条经验 获得超3个赞

应该有另一个名为“ingredient_recipe”的表。多对多关系项目将保存在此处。



查看完整回答
反对 回复 2023-10-15
  • 2 回答
  • 0 关注
  • 61 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信