【问题标题】:Million ManyToMany Entries - Memory Problems百万多对多条目 - 内存问题
【发布时间】:2013-05-14 13:51:54
【问题描述】:

我开发了一种“Statistics-Web”。

例如,我有一些博客条目,每个访问者都有一个额外的统计条目。

示例博客实体:

/**
 * @ORM\ManyToMany(targetEntity="Statistic", inversedBy="blogid")
 * @ORM\JoinTable(name="blog_statistics")
 */
private $statistics;

示例统计实体:

/**
 * @ORM\ManyToMany(targetEntity="Blog", mappedBy="statistics")
 */
private $blog;

在统计实体中,我有更多字段,例如“时间、用户、ip”。 在博客实体中,我有“文本、标题、时间”等字段。

一开始我有 1 个条目。 一切正常/良好。

一周后,我有 2 个博客条目的 5.000 个条目 (DB)。 (每个博客条目 2.500) 我遇到了 php 内存问题。

我认为教义试图将所有 2.500 个条目加载到 RAM/缓存中。 但我只需要最后一个来获取“上次访问”信息。 如果我需要的话,我可以得到其余的条目。 (统计概览)

什么是最好的“限制”条目? 当前调用:“Repository->fetchAll”

【问题讨论】:

  • 直接在您的查询中进行排序和限制,因此只有您搜索的行被水合到 php 对象中。
  • 我有 2 个条目......或者你的意思是像 @ORM\Limit(1) 这样的注解
  • 您可以发布更多代码,您在哪里调用 fetchAll 以及在哪个 repo 上?
  • A "repository->fetchAll()" is all :D 想象一个包含所有博客条目的列表..." for blogentry in blogentries ... {{ blogentry.title }} ... endfor " 没有规范 ...
  • 请发布带有所有 for 循环的控制器/模板代码。我认为您正在循环遍历所有 5k 条目,这就是问题所在。

标签: symfony doctrine-orm doctrine many-to-many limit


【解决方案1】:

解决方案很明显:

$lastStatisticsRecord = $repository->createQueryBuilder('s')
        ->orderBy('s.time', 'DESC')
        ->setMaxResults(1)
        ->getQuery()
        ->execute();

此查询将仅选择表中的最后一个统计实体。 如果需要获取最后一个统计条目的博客条目,只需做一个 JOIN 语句:

 $lastStatisticsRecord = $repository->createQueryBuilder('s')
        ->select(array('s', 'b'))
        ->leftJoin('s.blogid', 'b')
        ->orderBy('s.time', 'DESC')
        ->setMaxResults(1)
        ->getQuery()
        ->execute();

【讨论】:

  • 好的。如果我使用你的代码,我必须删除“private $statistics;”从实体。对?或者不加载 QueryBuilder 的多对多连接?那就完美了:)
  • 不,保留您现在的关系描述,只需使用我提供的查询;)
【解决方案2】:

问题已解决...

仅在多对多关系中使用“获取”选项:

@ORM\ManyToMany(targetEntity="Statistic", inversedBy="blogid", fetch="EXTRA_LAZY")

然后你可以使用这个函数来获取最新的统计条目:

public function getLatestStatistic()
{
    $cur = array();
    if(count($this->getStatistics()) > 0)
    {
        $cur = $this->getStatistics()->slice(count($this->getStatistics()) - 1, 1);
    }
    return count($cur) > 0 ? $cur[0] : null;
}

【讨论】:

    猜你喜欢
    • 2011-10-12
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多