Doctrine: How to insert foreign key value

你说的曾经没有我的故事 提交于 2019-12-12 04:53:34

问题


I have two tables in my database: sliders and images. One slider can have many images, so the structure of tables is:

 ---------      --------
| SLIDERS |    | IMAGES |
 ---------      --------
|   id    |    |   id   |
 ---------      --------
|  title  |    | title  |
 ---------      --------
               |  sid   |
                --------
SID is a foreign key associated to id in "SLIDERS" table.

In entities I put bidirectional relationships OneToMany and ManyToOne, so fetched Slider result would contain Images Objects that belong to him, and Images would contain Slider Object that belongs to them.

Sliders Entity:

class Sliders
{

...

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

Images Entity:

class Images
{

...

/**
 * @ORM\ManyToOne(targetEntity="Sliders", inversedBy="images")
 * @ORM\JoinColumn(name="sid", referencedColumnName="id")
 */
protected $slider;

It is really comfortable for fetching. But now I can't understand how can I INSERT sid into Images table, since I don't have this field in my entity except $slider that returns Object. Is it possible to do it using this $slider?


回答1:


Following function you should have already in your Slider entity (or similar).

public function addImage(Image $image)
{
    $image->setSlider($this); // This is the line you're probably looking for
    $this->images[] = $image;

    return $this;
}

What it does is if you persist the entity it writes the ID of the Slider (sid) into your Image.



来源:https://stackoverflow.com/questions/26653862/doctrine-how-to-insert-foreign-key-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!