ManyToMany 与 Symfony 5 的关系:不保存

对于我的项目,我创建了 2 个实体:配方和成分。它们是多对多关系。 mysql 架构

我从控制台生成了所有内容(实体和 CRUD)。但是,我无法保存食谱的成分,“成分”字段不保存任何内容,只保存日期和名称。

我尝试在我的实体中添加“cascade={”persist”}”,但它不起作用。预先感谢您的帮助 !

成分.php

<?php


namespace 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;


    }

}


慕斯王
浏览 64回答 2
2回答

ABOUTYOU

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

皈依舞

应该有另一个名为“ingredient_recipe”的表。多对多关系项目将保存在此处。
打开App,查看更多内容
随时随地看视频慕课网APP