【问题标题】:Symfony2 - Using getArrayResult() results in a missing field from dbSymfony2 - 使用 getArrayResult() 会导致 db 中缺少字段
【发布时间】:2014-03-29 05:39:17
【问题描述】:

可以在这方面使用一些指导 - 一些上下文,我正在向我正在练习的一个简单博客添加一个简单的分页代码,但是当从分页中使用 getArrayResult() 时,它缺少一个字段('cmets')我需要将其传递到我的树枝文件中。

当使用 getRepository(获取所有)时,它可以根据需要返回 'cmets' 字段。评论是它自己的表格,与博客分开。有什么办法可以让这个工作与分页的设置方式一起工作?

非常感谢任何帮助。

cmets 字段设置为我的博客实体的“一对多”。

博客实体

/**
 * @ORM\OneToMany(targetEntity="Comment", mappedBy="blog")
 */
protected $comments;

评论实体

/**
 * @ORM\ManyToOne(targetEntity="Blog", inversedBy="comments")
 * @ORM\JoinColumn(name="blog_id", referencedColumnName="id")
 */
protected $blog;

控制器获取存储库

$em = $this->getDoctrine()->getManager();

$blogs = $em->getRepository('GeneralSymProjectBundle:Blog')
    ->getLatestBlogs();

分页代码

    $page = $request->get('page');

    $count_per_page = 5;
    $total_count = $this->getTotalBlogs();
    $total_pages = ceil($total_count/$count_per_page);

    if (!is_numeric($page)) {
        $page = 1;
    } else {
        $page = floor($page);
    }

    if ($total_count <= $count_per_page) {
        $page = 1;
    }

    if (($page * $count_per_page) > $total_count) {
        $page = $total_pages;
    }

    $offset = 0;

    if ($page > 1) {
        $offset = $count_per_page * ($page - 1);
    }

    $em = $this->getDoctrine()->getManager();

    $blogQuery = $em->createQueryBuilder()
        ->select('b')
        ->from('GeneralSymProjectBundle:Blog', 'b')
        ->setFirstResult($offset)
        ->setMaxResults($count_per_page);

    $blogFinalQuery = $blogQuery->getQuery();

    $blogPage = $blogFinalQuery->getArrayResult();

存储库转储(返回 cmets)

object(stdClass)[875]
  public '__CLASS__' => string 'General\SymProjectBundle\Entity\Blog' (length=36)
  public 'id' => int 2
  public 'title' => string 'Another blog post' (length=17)
  public 'author' => string 'KK' (length=2)
  public 'blog' => string '...' (length=...)
  public 'image' => string 'practice.jpg' (length=12)
  public 'tags' => string 'symfony, php, blog, dummy text, fantasy, features, symproject' (length=61)
  public 'comments' => string 'Array(2)' (length=8)
  public 'created' => string 'DateTime' (length=8)
  public 'updated' => string 'DateTime' (length=8)
  public 'slug' => string 'another-blog-post' (length=17)

分页转储(缺少 cmets 字段)

'id' => int 2
  'title' => string 'Another blog post' (length=17)
  'author' => string 'KK' (length=2)
  'blog' => string '... (length=...)
  'image' => string 'practice.jpg' (length=12)
  'tags' => string 'symfony, php, blog, dummy text, fantasy, features, symproject' (length=61)
  'created' => string 'DateTime' (length=8)
  'updated' => string 'DateTime' (length=8)
  'slug' => string 'another-blog-post' (length=17)

Index.html.twig

{# src/General/SymProjectBundle/Resources/views/Default/index.html.twig #}
{% extends 'GeneralSymProjectBundle::layout.html.twig' %}

{% block body %}
{% for blog in blogPage %}
    <div class="container">
        <div class="row">
            <div class="col-sm-8 blog-main">
                <div class="blog-post">


                    <h2 class="blog-post-title">{{ blog.title }}</h2>
                        <p class="blog-post-meta"><time datetime="{{ blog.created|date('c') }}">{{ blog.created|date('l, F j, Y') }}</time> by <a href="#">{{ blog.author }}</a></p>

                    <div class="comment">
                        <p><small>Comments: {{ blog.comments|length }}</small></p>
                    </div>

                        <p>{{ blog.blog|truncate(350, true) }}</p><br>

                    <div class="tags">
                        <p><strong>Tags: </strong><span class="highlight">{{ blog.tags }}</span></p>
                    </div>
                        <p class="continue"><a href="{{ path('general_sym_project_show', { 'id': blog.id, 'slug': blog.slug }) }}">More reading&raquo </a></p>
                    <hr>

                </div><!-- /.blog-post -->
            </div>
        </div>
    </div>
{% endfor %}
{% endblock %}

{% block sidebar %}
{{ parent() }}

{% endblock %}

【问题讨论】:

  • 这个命令说明了什么:app/console dictionary:schema:validate ?你的架构好吗?
  • [映射] OK - 映射文件正确。 [数据库] OK - 数据库架构与映射文件同步。这不是架构的问题,而是我调用数据的方式,并且在使用 getArrayResult() 时它不喜欢“cmets”的关系表数据,尝试使用当前分页设置来做到这一点。

标签: symfony doctrine-orm pagination


【解决方案1】:

我猜commments 是一个以博客ID 作为外键的单独表。将此添加到分页代码中可能会为您的博文获取 cmets。

foreach $blogPage as $blog{
  $blog_id = $blog["id"] // U might have to modify these based on the result you get.
  $commentRepository = $this->getDoctrine()
    ->getRepository('GeneralSymProjectBundle:Comment'');

  $comments []= $repository->findByBlogId($blog_id);
}

将 cmets 作为单独的变量传递,并为树枝尝试这个:

{% block body %}
    {% for blog in blogPage %}
                      .
                      .

                <div class="comment">
                    <p><small>Comments: {{ comments[loop.index0]|length }}</small></p>
                            {% for comment in  comments[loop.index0] %}
                                 //display the comments here if you need
                            {% endfor %}
                 </div>
                      .
                      .
                      .

    {% endfor %}
{% endblock %}

查看http://symfony.com/doc/current/book/doctrine.html 了解更多关于学说过滤的信息

【讨论】:

  • 是的,cmets 是一个单独的表,以 blog_id 作为外键。
  • 不工作。当我尝试使用 $blog["blog_id"] 时,出现以下错误“ContextErrorException: Notice: Undefined index: blogId in”。
  • 在此之前,我在 $blog 上做了一个转储,它给出了相同的结果,没有评论字段,也没有 blog_id。
  • 检查 $blog 数组的结构并使用具有 blog id 的字段将 blog id 获取到 $blog_id 。我已编辑。立即尝试
  • 奇怪,它现在可以工作了……不知道为什么在使用 {{ cmets[loop.index0]|length }} 之前它没有工作。感谢 Manoj 花费时间和耐心向我展示解决方法。先生,欣赏!
【解决方案2】:

如果你使用getArrayResult,你不会得到关系表的数据。

这肯定对你有用。

$blogQuery = $em->createQueryBuilder()
        ->select('b, c')
        ->from('GeneralSymProjectBundle:Blog', 'b')
        ->leftJoin('b.Comments', 'c');

【讨论】:

  • 对此进行测试,当我进行转储时出现以下错误 - “[Semantical Error] line 0, col 69 near 'c': Error: Class General\SymProjectBundle\Entity\Blog has no名为 Comments 的关联"
  • Correction 将 b.Comments 更改为 b.cmets 并且我得到了成功的转储,但是当我添加 ->setFirstResult($offset) 和 ->setMaxResults($count_per_page) 我现在仅限于数据库中的 2 行??
  • 澄清一下,它确实给了我我正在寻找的东西,如上所述,但作为警告,它与分页效果不佳,并将我的帖子限制为 2 而不是 5 中设置的最大限制。
猜你喜欢
  • 1970-01-01
  • 2020-10-31
  • 2021-11-21
  • 2018-06-08
  • 1970-01-01
  • 2011-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多