如果多与学说一起插入到联结表中?

时间:2018-04-10 20:33:26

标签: symfony insert doctrine many-to-many junction-table

我正在尝试插入一个名为 post_post_category 的联结表,它基于发布 PostCategory 表[多对多],我设法执行插入但问题是,当我添加新帖子时,它会创建一个新类别。

发布实体:

class Post
{

...

 /**
 *  @ORM\ManyToMany(targetEntity="PostCategory", cascade={"persist"})
 *  @ORM\JoinTable(name="post_post_category",
 *      joinColumns={@ORM\JoinColumn(name="post_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="post_category_id", referencedColumnName="id")}
 *   )
 */
private $categories;

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

...

public function getCategories(): ?PostCategory
{
    return $this->categories;
}

public function addCategory(PostCategory $category): self
{
    $this->categories->add($category);

    return $this;
}
}

类别实体:

class PostCategory
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=60)
     */
    private $category_description;

    public function getId()
    {
        return $this->id;
    }

    public function getCategoryDescription(): ?string
    {
        return $this->category_description;
    }

    public function setCategoryDescription(string $category_description): self
    {
        $this->category_description = $category_description;

        return $this;
    }    
}

控制器:

...

$category->setCategoryDescription('New category');
$post->addCategory($category);

$database_manager->persist($post);
$database_manager->flush();

如何在联结表中插入现有类别?

1 个答案:

答案 0 :(得分:0)

要将现有类别添加到帖子,您必须从数据库中检索该类别

public static bool WaitForElementVisible(IWebDriver driver, IWebElement ele)
{
    try
    {
        var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
        wait.Until(d => (bool)(ele as IWebElement).Displayed);
        return true;
    }
    catch (NoSuchElementException)
    {
        return false;
    }
}