原则:如何插入外键值 [英] Doctrine: How to insert foreign key value

查看:149
本文介绍了原则:如何插入外键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有两张表:滑块图像。一个滑块可以有很多图像,所以表的结构是:

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.

在实体中,我将双向关系 OneToMany ManyToOne ,所以获取的Slider结果将包含属于他的 Images Objects ,而图像将包含 Slider Object 属于他们。

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.

滑块实体:

class Sliders
{

...

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

图片实体:

class Images
{

...

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

提取真的很舒服。但是现在我不明白如何将 INSERT sid into Images 表,因为我的实体中没有这个字段,除了 $ slider 返回Object。有可能使用这个 $ 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?

推荐答案

功能你应该已经在你的Slider实体(或类似的)。

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

它的作用是如果你坚持写实体的ID (sid)进入您的图像。

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

这篇关于原则:如何插入外键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆