dongxin1999 2016-02-22 06:12
浏览 48

Symfony Doctrine ORM ManyToMany - 带标签的博客 - 我没有从博客中获取所有标签,没有延迟加载

Doctrine lazy loading on manyToMany.

I'm using Application\Sonata\ClassificationBundle\Entity\Tag in my blog(post).

/**
     * @var string
     *
     * @ORM\ManyToMany(targetEntity="\Application\Sonata\ClassificationBundle\Entity\Tag", cascade={"persist"} )
     * @ORM\JoinTable( name="blog__post_tag" , 
     * joinColumns={ @ORM\JoinColumn( name="blog_post_id", referencedColumnName="id" )},
     * inverseJoinColumns={ @ORM\JoinColumn( name="tag_id", referencedColumnName="id" )}
     * )
     */
    private $tags;

Working code:

$q = $this->createQueryBuilder('p')
                ->select('p')
                ->innerJoin('p.tags', 't')
                ->where('t = :name')->setParameter('name', $tag)
                ->andWhere('p.isActive = :active')->setParameter('active', TRUE)
                ->orderBy('p.id', 'DESC');
        return $q->getQuery();

From this output query i use tags in twig. So i have to select post and tags. If i update the code to :

$q = $this->createQueryBuilder('p')
                ->select('p', 't')
                ->innerJoin('p.tags', 't')
                ->where('t = :name')->setParameter('name', $tag)
                ->andWhere('p.isActive = :active')->setParameter('active', TRUE)
                ->orderBy('p.id', 'DESC');
        return $q->getQuery();

I get only one tag.

INFO :

  • Working code uses more db query (1 more query).
  • Updated code works (no more query). But in result i get only one tag for all post.

Example :

  • "My First post " has tags ['one','two','three'].
  • "My Second post " has tags ['two'].

When i use first query. Works fine. But the doctrine lazy load code for tags. I get output for (query1) two = "My First post " has tags ['one','two','three']. , "My Second post " has tags ['two'].

When i use second query. The output for (query2) two = "My First post " has tags ['two']. , "My Second post " has tags ['two'].

I need all tags from the post. Currently i get only one tag form the post.

  • 写回答

2条回答 默认 最新

  • dongyao2001 2016-02-22 08:55
    关注

    It's like that because of INNER JOIN. Great answer about join types is here: https://stackoverflow.com/a/6188334/919567

    This version of query will work for you:

    $q = $this->createQueryBuilder('p')
        ->select('p', 't')
        ->leftJoin('p.tags', 't')
        ->where('t = :name')->setParameter('name', $tag)
        ->andWhere('p.isActive = :active')->setParameter('active', TRUE)
        ->orderBy('p.id', 'DESC');
    
    return $q->getQuery();
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度