需要初学者实体关系协助

时间:2013-08-16 15:23:49

标签: php symfony doctrine-orm

我是学说的新手,并且很难设法建立我的第一个实体关系/协会。

我想要以下两个表:

Kitchen
- ID
- Name
- Description
- MainImage

KitchenImage
- ID
- KitchenID (ref Kitchen.ID)
- Image

每个厨房都会有一张主照片和一副子照片。

目前这是我的两个学说文件(删除了get和setters进行格式化):

厨房

/**
 * @ORM\Entity
 * @ORM\Table(name="kitchen")
 */
class Kitchen
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $name;

    /**
     * @ORM\Column(type="text")
     */
    protected $description;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $image;

    /**
     * @ORM\OneToMany(targetEntity="KitchenImage", mappedBy="kitchen")
     */
    protected $images;

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

Kitchen_Image

/**
 * KitchenImage
 *
 * @ORM\Table(name="kitchen_image")
 * @ORM\Entity
 */
class KitchenImage
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="image", type="string", length=255)
     */
    protected $image;

    /**
     * @ORM\ManyToOne(targetEntity="Kitchen", inversedBy="images")
     * @ORM\JoinColumn(name="kitchen_id", referencedColumnName="id")
     */
    protected $kitchen;
}

PHP功能:

public function createAction()
    {
        $kitchen = new Kitchen();
        $kitchen->setName('Example Kitchen');
        $kitchen->setDescription('Big amount of text to go here...');
        $kitchen->setImage('front-image.jpg');

        $image1 = new KitchenImage();
        $image1->setImage('1.jpg');

        $image2 = new KitchenImage();
        $image2->setImage('2.jpg');

        $kitchen->addImage($image1);
        $kitchen->addImage($image2);

        $em = $this->getDoctrine()->getManager();
        $em->persist($kitchen);
        $em->flush();

        return new Response('success');
    }

错误回复

A new entity was found through the relationship 'PWD\WebsiteBundle\Entity\Kitchen#images' that was not configured to cascade persist operations for entity: PWD\WebsiteBundle\Entity\KitchenImage@0000000009670754000000003a9b3dc9. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'PWD\WebsiteBundle\Entity\KitchenImage#__toString()' to get a clue.

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您需要替换这段代码:

$em = $this->getDoctrine()->getManager();
$em->persist($kitchen);
$em->flush();

有了这个:

$em = $this->getDoctrine()->getManager();
$em->persist($image1);
$em->persist($image2);
$em->persist($kitchen);
$em->flush();