Doctrine ManyToMany - 加入多种关系

时间:2014-04-23 21:28:22

标签: symfony doctrine-orm

我想知道是否有办法使用2个ManyToMany关系从一个表中获取记录(通过示例可能更容易解释)。

我有3个模型:文章,主题和类型,并且Article< - >之间存在ManyToMany关系。主题和文章< - >类型和我正在寻找的是获取分配给特定主题的文章的类型。我希望这是有道理的。

下面你可以看到我的实体的声明:

class Article
{
    /**
     * @var topics
     *
     * @ORM\ManyToMany(targetEntity="Topic")
     * @ORM\JoinTable(name="article_topic")
     */
    protected $topics;

    /**
     * @var types
     *
     * @ORM\ManyToMany(targetEntity="Type", inversedBy="articles")
     * @ORM\JoinTable(name="article_type")
     */
    protected $types;
}  

class Topic
{
    /**
     * @var Article
     *
     * @ORM\ManyToMany(targetEntity="Article")
     */
    private $articles;
}

class Type
{
    /**
     * @var Article
     *
     * @ORM\ManyToMany(targetEntity="Article")
     */
    private $articles;
}  

现在我的TypeRepository中有一个方法:(更新)

public function getByTopic($topic = null)
{
    $qb = $this->getEntityManager()->createQueryBuilder()
        ->select('t')
        ->from('Type', 't');

    if ($topic) {
        $subqb = $this->getEntityManager()->createQueryBuilder()
            ->select('a.id')
            ->from('Article', 'a')
            ->innerJoin('a.topics', 'atop', 'WITH', 'atop.id = :topicId')
        ;
        $qb->innerJoin('t.articles', 'ta')
            ->where($qb->expr()->in('ta.id', $subqb->getDql())
            ->setParameter('topicId', $topic->getId());
    }

    return $qb->getQuery()->getResult();
}  

我收到错误:PathExpression无效。期望StateFieldPathExpression或SingleValuedAssociationField(但是它显示了来自twig模板的行,我正在努力找到这个的底部)。

问题是如何将类型分配给属于特定主题的文章。

任何建议表示赞赏 谢谢。

1 个答案:

答案 0 :(得分:0)

为什么不这样做:

$qb = $this->getEntityManager()->createQueryBuilder('ty')  
                         ->addSelect('ty');  
if ($topic) {  
  $qb->join('ty.articles','a')  
     ->addSelect('a')  
     ->join('a.topics','to')  
     ->addSelect('to')  
     ->where('to.id=:topic_id')  
     ->setParameter('topic_id',$topic);
}
return $qb->getQuery()->getResult();