You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Svelte中Dexie仅单个查询更新的原因及批量查询问题

为什么上一轮赛事无法响应更新?

你的lastFixtures和nextFixtures的liveQuery是在组件初始化时创建的,回调里的$leagueRound值只会取到初始状态的数值。之后leagueRound更新时,这两个查询不会自动重新执行。你看到下一轮能更新,大概率是因为推进游戏时间时,下一轮的赛事数据被修改,liveQuery检测到数据库变化触发了更新;但上一轮的数据没有变动,liveQuery不会主动重新查询新的轮次(比如leagueRound从n变n+1时,上一轮应该查n,但你的查询还停留在n-1)。

解决方法很简单,把两个liveQuery的赋值放到Svelte的响应式块里,这样leagueRound变化时会自动重新创建查询:

<script>
  import { liveQuery } from 'dexie'
  import { db } from '../../db'
  import { leagueRound } from '../../store'

  // 用响应式语句包裹,监听leagueRound变化
  $: lastFixtures = liveQuery(() =>
    db
      .fixtures
      .get($leagueRound - 1)
  )
  $: nextFixtures = liveQuery(() =>
    db
      .fixtures
      .get($leagueRound)
  )

  $: lastFixture = $lastFixtures?.fixtures.filter(f => f.home.id === 15 || f.away.id === 15)[0]
  $: nextFixture = $nextFixtures?.fixtures.filter(f => f.home.id === 15 || f.away.id === 15)[0]
</script>

为什么单个anyOf查询没有返回结果?

通常是以下两个原因:

  1. 主键字段名不匹配:你之前用db.fixtures.get($leagueRound),说明fixtures表的主键应该是round(轮次)而非id。但你的查询写的是where('id'),这会查询不存在的字段,自然返回空数组。把字段名改成实际的主键名,比如:
liveQuery(() => 
  db
    .fixtures
    .where('round') // 替换成你的实际主键字段名
    .anyOf([$leagueRound - 1, $leagueRound])
    .toArray()
)
  1. 轮次数据不存在:检查$leagueRound -1和$leagueRound对应的轮次是否真的在数据库中有数据,比如刚开局时leagueRound=1,$leagueRound-1=0可能没有数据,导致返回空数组。

如果查询正常返回数据,后续可以按轮次排序后提取对应赛事:

$: fixturesPair = liveQuery(() => 
  db
    .fixtures
    .where('round')
    .anyOf([$leagueRound - 1, $leagueRound])
    .toArray()
)

$: [lastFixtures, nextFixtures] = $fixturesPair?.sort((a,b) => a.round - b.round) || [null, null]
$: lastFixture = lastFixtures?.fixtures.filter(f => f.home.id ===15 || f.away.id ===15)[0]
$: nextFixture = nextFixtures?.fixtures.filter(f => f.home.id ===15 || f.away.id ===15)[0]

内容的提问来源于stack exchange,提问作者NickH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 19:15:51