在 Symfony 中防止 Doctrine 的查询缓存
在我的 Symfony/Doctrine 应用程序中,我有一个按 RANDOM() 排序的查询。我多次调用相同的方法,但看起来查询的结果正在被缓存。
这是我的相关代码:
$query = $table->createQuery('p')
->select('p.*, RANDOM() as rnd')
->orderBy('rnd')
->limit(1)
->useQueryCache(null)
->useResultCache(null);
$result = $query->fetchOne();
不幸的是,无论我将 null
传递给 useQueryCache
和 useResultCache
,每次都会返回相同的记录。我尝试使用 false
而不是 null
,但这也不起作用。最后,我还尝试同时调用 setResultCacheLifeSpan(0)
和 setResultCacheLifeSpan(-1)
,但这两个调用都没有效果。
由于我希望每次调用此方法时都选择不同的随机行,因此对如何防止缓存有何见解?
编辑:我还尝试调用clearResultCache()
,但这最终导致出现错误:“结果缓存驱动程序未初始化”。
编辑2:根据要求,以下是通过调用$query->getSqlQuery()
生成的SQL:
SELECT c.id AS c__id, c.name AS c__name, c.image_url AS c__image_url,
c.level AS c__level, c.created_at AS c__created_at, c.updated_at
AS c__updated_at, RANDOM() AS c__0 FROM cards c ORDER BY c__0 LIMIT 1
In my Symfony/Doctrine app, I have a query that orders by RANDOM(). I call this same method several times, but it looks like the query's result is being cached.
Here's my relevant code:
$query = $table->createQuery('p')
->select('p.*, RANDOM() as rnd')
->orderBy('rnd')
->limit(1)
->useQueryCache(null)
->useResultCache(null);
$result = $query->fetchOne();
Unfortunately, the same record is returned every time, regardless of me passing null
to both useQueryCache
and useResultCache
. I tried using false
instead of null
, but that didn't work either. Lastly, I also tried calling both setResultCacheLifeSpan(0)
and setResultCacheLifeSpan(-1)
, but neither call made a difference.
Any insight on how to prevent caching since I want a different random row to be selected each time I call this method?
Edit: I also tried calling clearResultCache()
, but that just ended up causing an error stating: "Result Cache driver not initialized".
Edit 2: As requested, here's the SQL generated by calling $query->getSqlQuery()
:
SELECT c.id AS c__id, c.name AS c__name, c.image_url AS c__image_url,
c.level AS c__level, c.created_at AS c__created_at, c.updated_at
AS c__updated_at, RANDOM() AS c__0 FROM cards c ORDER BY c__0 LIMIT 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
原来我是个白痴。我试图简化对这个问题的查询,但这样做时,我没有捕获真正的原因。我进行了
where()
和andWhere()
调用,条件组合导致仅匹配一条可能的记录。感谢大家抽出宝贵的时间回复,抱歉耽误了大家的时间!It turns out I'm a moron. I tried to simplify my query for this question, and in doing so, I didn't capture the true cause. I had a
where()
andandWhere()
call, and the combination of conditions resulted in only one possible record being matched. Thanks for taking the time to respond, everyone, sorry to have wasted your time!Doctrine 还会缓存您在同一请求/脚本运行中创建的实体。
例如:
print_r 将不包含您在睡眠期间所做的更改。
以下代码将删除这种内存缓存:
PS:添加此答案是因为我发现此主题试图解决上述问题。
Doctrine also caches entities you created in the same request/script run.
For instance:
The print_r will not contain the changes you made during the sleep.
The following code will remove that kind of memory cache:
PS: Added this answer because I found this topic trying to resolve above issue.