1

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?

Ignas Damunskis
  • 1,515
  • 1
  • 17
  • 44

1 Answers1

0

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.

Koalabaerchen
  • 555
  • 4
  • 15