Sytrfony3中的Doctrine2 ManyToMany关联查询

时间:2016-03-24 08:13:22

标签: php mysql doctrine-orm symfony

您好,欢迎Stackoverflowers?花卉?!没关系:)

前段时间我开始深入学习Symfony3,到目前为止,你在这里提出的问题对我来说已经足够了。但今天这一天已经到来,我个人有一个问题。

让我们勾勒出情况:

我正在为我的小型CMS开发一个简单的标记功能。 我希望我的文章(也可能是后来的其他内容)包含我附加到它们的一些标签。为了做到这一点,我用Doctrine创建了一组两个对象:文章& 标记(下面有些代码):

文章模型     

  namespace AppBundle\Entity;

  use Doctrine\ORM\Mapping as ORM;
  use Doctrine\Common\Collections\ArrayCollection;

/**
 * Article
 *
 * @ORM\Table(name="article")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ArticleRepository")
 */

class Article extends ContentItem
{
/**
 * @var string
 *
 * @ORM\Column(name="content", type="text")
 */
private $content;

/**
 *
 * @ORM\ManyToOne(targetEntity="ContentTypeDict", inversedBy="articles")
 * @ORM\JoinColumn(name="type_id", referencedColumnName="id", nullable=false)
 */
private $type;

/**
 * @ORM\ManyToMany(targetEntity="Tag", inversedBy="articles")
 * @ORM\JoinTable(name="tags_of_articles")
 */

protected $tags;

public function __construct()
{

    $this->tags = new ArrayCollection();

}
/**
 * Get id
 *
 * @return int
 */
public function getId()
{
    return $this->id;
}

/**
 * Set type
 *
 * @param boolean $type
 *
 * @return Article
 */
public function setType($type)
{
    $this->type = $type;

    return $this;
}

/**
 * Get type
 *
 * @return bool
 */
public function getType()
{
    return $this->type;
}

/**
 * Set content
 *
 * @param string $content
 *
 * @return Article
 */
public function setContent($content)
{
    $this->content = $content;

    return $this;
}

/**
 * Get content
 *
 * @return string
 */
public function getContent()
{
    return $this->content;
}

/**
 * Add tag
 *
 * @param \AppBundle\Entity\tag $tag
 *
 * @return Article
 */
public function addTag(\AppBundle\Entity\tag $tag)
{
    $this->tags[] = $tag;

    return $this;
}

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

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

标记模型     

namespace AppBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * Tag
 *
 * @ORM\Table(name="tag")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\TagRepository")
 */
class Tag
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, unique=true)
     */
    private $name;

    /**
     * @var int
     *
     * @ORM\Column(name="popularity", type="integer")
     */
    private $popularity;

    /**
     *
     * @ORM\ManyToMany(targetEntity="Article", mappedBy="tags")
     */
    private $articles;

    /**
     *
     * @ORM\ManyToMany(targetEntity="Asset", inversedBy="tags")
     * @ORM\JoinTable(name="assets_tags")
     */
    private $assets;


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

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Tag
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set popularity
     *
     * @param integer $popularity
     *
     * @return Tag
     */
    public function setPopularity($popularity)
    {
        $this->popularity = $popularity;

        return $this;
    }

    /**
     * Get popularity
     *
     * @return int
     */
    public function getPopularity()
    {
        return $this->popularity;
    }

    /**
     * Add content
     *
     * @param \AppBundle\Entity\ContentItem $content
     *
     * @return Tag
     */
    public function addContent(\AppBundle\Entity\ContentItem $content)
    {
        $this->content[] = $content;

        return $this;
    }

    /**
     * Remove content
     *
     * @param \AppBundle\Entity\ContentItem $content
     */
    public function removeContent(\AppBundle\Entity\ContentItem $content)
    {
        $this->content->removeElement($content);
    }

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

    /**
     * Add article
     *
     * @param \AppBundle\Entity\ContentItem $article
     *
     * @return Tag
 */
public function addArticle(\AppBundle\Entity\ContentItem $article)
{
    $this->articles[] = $article;

    return $this;
}

/**
 * Remove article
 *
 * @param \AppBundle\Entity\ContentItem $article
 */
public function removeArticle(\AppBundle\Entity\ContentItem $article)
{
    $this->articles->removeElement($article);
}

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

/**
 * Add asset
 *
 * @param \AppBundle\Entity\ContentItem $asset
 *
 * @return Tag
 */
public function addAsset(\AppBundle\Entity\ContentItem $asset)
{
    $this->assets[] = $asset;

    return $this;
}

/**
 * Remove asset
 *
 * @param \AppBundle\Entity\ContentItem $asset
 */
public function removeAsset(\AppBundle\Entity\ContentItem $asset)
{
    $this->assets->removeElement($asset);
}

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

这些对象是相关的,您可以看到关联 ManyToMany 与名为'tags_of_articles'的表

现在有了这两个对象,我希望能够通过提供标签或(可能稍后)一堆标签来获得文章。

为此,我在 ArticleController

中编写了一个简短的函数
 /**
 * @Route("/showArticlesByTag/{tag}")
 */
public function showArticlesByTag($tag)
{
    $em = $this->getDoctrine()->getManager();
    $tagRepo = $em->getRepository('AppBundle:Tag');
    $tagData = $tagRepo->findOneBy(array('name' => $tag,));
    $dataRepo = $em->getRepository('AppBundle:Article');
    $data = $dataRepo->findOneBy(array('tags' => $tagData->getId(),));

    var_dump($data);
    //return $this->render('AppBundle:Article:show_article.html.twig', array( ));
}

执行结果,让我们说

  

本地主机/用户〜/ MyCMS /网络/ app_dev.php / showArticlesByTag / Architecto

(标签表中存在标签 Architecto

我得到一个例外:

  

执行'SELECT t0.content AS content_1时发生异常,   t0.id AS id_2,t0.title AS title_3,t0.description AS description_4,   t0.enabled AS enabled_5,t0.type_id AS type_id_6 FROM article t0 WHERE   tags_of_articles.tag_id =?限制1'与params [3]:

     

SQLSTATE [42S22]:找不到列:1054未知列   'where子句'中的'tags_of_articles.tag_id'

在结尾处我附上了我在SQL中的表结构:doctrine:

- --------------------------------------------------------

--
-- Table structure for table `article`
--

CREATE TABLE IF NOT EXISTS `article` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `type_id` int(11) NOT NULL,
 `content` longtext COLLATE utf8_unicode_ci NOT NULL,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `description` longtext COLLATE utf8_unicode_ci NOT NULL,
 `enabled` tinyint(1) NOT NULL,
 PRIMARY KEY (`id`),
 KEY `IDX_23A0E66C54C8C93` (`type_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;

-- --------------------------------------------------------

--
-- Table structure for table `tag`
--

CREATE TABLE IF NOT EXISTS `tag` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `popularity` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UNIQ_389B7835E237E06` (`name`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=5 ;

-- --------------------------------------------------------

--
-- Table structure for table `tags_of_articles`
--

CREATE TABLE IF NOT EXISTS `tags_of_articles` (
  `tag_id` int(11) NOT NULL,
  `article_id` int(11) NOT NULL,
  KEY `IDX_D429AC71BAD26311` (`tag_id`),
  KEY `IDX_D429AC717294869C` (`article_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

现在的问题是:我做错了什么?或许,我在这里错过了什么?

2 个答案:

答案 0 :(得分:0)

可能还有其他方法可以实现这一点,但我会通过向ArticleRepository添加方法findByTags来实现:

像这样添加一个方法到你的ArticleRepository(你没有自定义存储库?检查一下:Custom Repository Classes):

class ArticleRepository extends EntityRepository
{
    // ...

    public function findyByTags(array $tags)
    {
        $qb = $this->createQueryBuilder('a');
        $qb->join('a.tags', 't');

        for($i = 0; $i < count($tags); $i++) {
            $qb->andWhere($qb->expr()->eq('t.name', ':tag' . $i));
            $qb->setParameter('tag' . $i, $tags[$i]);
        }
        return $qb->getQuery()->getResult();
    }
}

在您的控制器中,您可以像这样使用它:

public function showArticlesByTag($tag)
{
    $dataRepo = $this->getDoctrine()->getRepository('AppBundle:Article');
    $data = $dataRepo->findByTags(array($tag));

    // ...
}

如果您将多个标记传递给此方法,则文章必须返回所有标记。 这段代码可能有错误,因为我当然无法测试它。但我希望它得到我的观点。 ; - )

答案 1 :(得分:0)

我似乎需要更改行

$data = $dataRepo->findOneBy(array('tags' => $tagData->getId(),));

如下:

$data = $dataRepo->findBy(array('tag' => $tagData));
相关问题