Symfony2 - 选择标签以显示帖子

时间:2014-05-12 22:16:13

标签: symfony doctrine-orm tags blogs entity-relationship

我尝试设置可选标签来显示/显示链接到标签的博客。

我做错了什么?是教条​​查询的问题还是在实体方面如何设置?

我收到以下错误:

ContextErrorException: Notice: Undefined index: joinColumns in /.../vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 1665

这是我正在使用的当前查询:

public function tagAction($tag)
{
    $em = $this->getDoctrine()->getManager();

    $tags = $em->getRepository('AcmeBundle:Blog')
        ->findByTags($tag);

    $blogs = $tags->getBlogs();

    return array(
        'blogs' => $blogs,
    );
}

我的实体设置:(设置为ManyToMany / ManyToMany)

标签:

/**
 * @ORM\ManyToMany(targetEntity="Blog", mappedBy="tags")
 */
protected $blogs;

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

/**
 * Add blogs
 *
 * @param \AcmeBundle\Entity\Blog $blogs
 * @return Tag
 */
public function addBlog(\AcmeBundle\Entity\Blog $blogs)
{
    $this->blogs[] = $blogs;

    return $this;
}

/**
 * Remove blogs
 *
 * @param \AcmeBundle\Entity\Blog $blogs
 */
public function removeBlog(\AcmeBundle\Entity\Blog $blogs)
{
    $this->blogs->removeElement($blogs);
}

/**
 * Get blogs
 *
 * @return \Doctrine\Common\Collections\Collection 
 */
public function getBlogs()
{
    return $this->blogs;
}

博客:

/**
 * @ORM\ManyToMany(targetEntity="Tag", inversedBy="blogs")
 * @ORM\JoinColumn(name="tag_id", referencedColumnName="id")
 */
protected $tags;

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

/**
 * Add tags
 *
 * @param \AcmeBundle\Entity\Tag $tags
 * @return Blog
 */
public function addTag(\AcmeBundle\Entity\Tag $tags)
{
    $this->tags[] = $tags;

    return $this;
}

/**
 * Remove tags
 *
 * @param \AcmeBundle\Entity\Tag $tags
 */
public function removeTag(\AcmeBundle\Entity\Tag $tags)
{
    $this->tags->removeElement($tags);
}

/**
 * Get tags
 *
 * @return \Doctrine\Common\Collections\Collection 
 */
public function getTags()
{
    return $this->tags;
}

2 个答案:

答案 0 :(得分:1)

而不是查询博客使用标记。

$em = $this->getDoctrine()->getManager();

$tags = $em->getRepository('AcmeBundle:Tag')
    ->findOneByTag($tag);

$blogs = $tags->getBlogs();

return array(
    'blogs' => $blogs,
);

答案 1 :(得分:0)

我认为发生此错误是因为您在ManyToMany关联中有错误的注释:

/**
 * @ORM\ManyToMany(targetEntity="Tag", inversedBy="blogs")
 * @ORM\JoinColumn(name="tag_id", referencedColumnName="id")
 */
protected $tags;

对于ManyToMany关联,我使用如下代码:

/**
 * @ManyToMany(targetEntity="Tag")
 * @JoinTable(name="blogs_tags",
 *      joinColumns={@JoinColumn(name="blog_id", referencedColumnName="id")},
 *      inverseJoinColumns={@JoinColumn(name="tag_id", referencedColumnName="id")}
 *      )
 */
protected $tags;

这是您在http://docs.doctrine-project.org/en/2.0.x/reference/association-mapping.html

中可以看到的Doctrine官方文档中的代码