php - Symfony3 多对多关联查询中的 Doctrine2

标签 php mysql doctrine-orm symfony

您好,欢迎光临 Stackoverflowers?花朵?!没关系:)

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

那么让我们勾勒一下情况:

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

文章模型

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

作为执行的结果,比方说

localhost/~user/MyCMS/web/app_dev.php/showArticlesByTag/Architecto

(标记表中存在标记 Architecto)

我得到一个异常(exception):

An exception occurred while executing '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 = ? LIMIT 1' with params [3]:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tags_of_articles.tag_id' in 'where clause'

在最后,我附上了 SQL 中的表结构:

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

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

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

最佳答案

可能还有其他方法可以实现这一点,但我会通过向您的 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();
    }
}

在你的 Controller 中你可以像这样使用它:

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

    // ...
}

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

关于php - Symfony3 多对多关联查询中的 Doctrine2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36195677/

相关文章:

php - 使用 CSS 在缩略图上播放按钮

其他数据库上的 PHP PDO LEFTJOIN

php - 如何将两个sql查询合并为一个具有可变限制的sql查询

mysql - my.ini 中的 O_Direct 启动崩溃

php - 使用 MIN 函数的 Symfony 最低用户出价?

postgresql - 使用 IS DISTINCT FROM 的 Symfony 原则

php - 在 PHP 中如何获取包含 PREPARE 和 EXECUTE 的 SQL 查询返回的行?

javascript - 下拉自动选择页面到页面

php - 无法使用 PHP 和 MySQL 获取记录

php - 2 个表的 Doctrine 2 映射,错误