Symfony 2 - 如何在Twig模板中显示已连接的Doctrine实体

时间:2014-08-04 19:34:58

标签: php symfony doctrine-orm twig

  1. 如何在树枝中检索实体数据?我选择了两个实体,新闻和评论,但在树枝上,我只能从新闻实体获取数据。 (例如:"来自Twig")
  2. 如何查看获取的实体对象中的内容(例如:来自Controller的$ fetched_news变量)。我尝试过:print_r($ fetched_news)或{{dump(fetched_news}},但在第一个例子中,我得到了完整的代码屏幕,在第二个应用程序中被暂停。
  3. 在新闻和评论实体中,有一个名为' content'的列。如何从这列中获取数据?我正在尝试这样的事情:
  4.   

    fetched_news.comments.content

      

    fetched_news.news.content

    我在很多页面上都在寻找答案,但我找不到有趣的东西。

    来自树枝:

    {% for news in fetched_news %}
       <div class="col-md-5">
            <p class="news_title">{{ news.title }}</p>
            {{ (news.content|slice(0,600))|raw }}
    
             {{ news.ratePlus }} {# CAN'T GET THIS!#}
        {% else %}
    {% endfor %}
    

    来自控制器:

        public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery("SELECT n, a FROM BlogAdminBundle:News n JOIN n.comments a");
        $fetched_news = $query->getResult();
    
    
        return array('fetched_news' => $fetched_news);
    }
    

    Web Profiler中的代码

    SELECT 
    n0_.id AS id0, 
    n0_.content AS content1, 
    n0_.title AS title2, 
    n0_.date_add AS date_add3, 
    n0_.date_active AS date_active4, 
    n0_.settings AS settings5, 
    c1_.id AS id6, 
    c1_.content AS content7, 
    c1_.date_add AS date_add8, 
    c1_.rate_plus AS rate_plus9, 
    c1_.rate_minus AS rate_minus10, 
    n0_.user_id AS user_id11, 
    c1_.user_id AS user_id12, 
    c1_.news_id AS news_id13 
    FROM 
    News n0_ 
    INNER JOIN Comments c1_ ON n0_.id = c1_.news_id
    

    感谢您的帮助!

    实体类评论:

     /**
     * @ORM\ManyToOne(targetEntity="News", inversedBy="comments")
     * @ORM\JoinColumn(name="news_id", referencedColumnName="id")
     */
    protected $news;
    

    实体类新闻:

     /**
     * @ORM\OneToMany(targetEntity="Comments", mappedBy="news")
     */
    protected $comments;
    public function __construct()
    {
        $this->comments = new \Doctrine\Common\Collections\ArrayCollection();
    }
    

1 个答案:

答案 0 :(得分:3)

给出以下代码:

$repository = $this->getDoctrine()->getRepository('BlogAdminBundle:News');

$query = $repository->createQueryBuilder('p') 
    ->where('p.date_active < :date') 
    ->setParameter('date', new \DateTime()) 
    ->getQuery(); 

$fetched_news = $query->getResult(); 

这应该在树枝上工作:

{% for news_article in fetched_news %} 

    {{ news_article.content }}

    {% for comment in news_article.comments %}
        {{ comment.content }}
    {% endfor %}

{% endfor %}

您的每篇新闻文章都有一系列评论。我认为您只是与$fetched_news变量=)混淆了一下。

编辑:我的代码中有一个小错误。我在外部循环中有fetched_news.news,那应该只是feteched_news,因为该变量是新闻文章的数组。