Solidity如何通过两个参数从mapping中查询address对应matchSelected的数据
问题核心原因
你当前的查询逻辑不生效,是因为结构体设计没有将玩家的投注记录和比赛ID做绑定:Player结构体顶层的amountBet、matchSelected等都是单值字段,只能存储一条投注数据,无法满足一个玩家参与多场比赛的查询需求。同时你定义的Bets映射使用无意义的uint作为索引键,和matchSelected没有关联,自然无法通过比赛ID查询到对应记录。
调整方案
1. 优化结构体设计
将Player中Bets映射的索引键改为uint16类型,直接用比赛IDmatchSelected作为键,实现比赛ID和投注记录的直接绑定,同时移除Player顶层冗余的单值投注字段,避免数据冲突。
修改后的核心结构体代码如下:
struct Bet { uint256 amountBet; uint16 matchSelected; uint16 resultSelected; } struct Player { uint numFunders; // 用比赛ID作为映射键,可直接通过matchSelected索引对应投注 mapping (uint16 => Bet) bets; } // 其余全局变量保持不变 mapping(address => Player) public playerInfo; mapping(uint16 => bool) matchBettingActive; address[] public players; address public owner;
2. 重写查询函数
现在可以直接通过两个入参分别索引玩家和对应比赛的投注记录:
function getPlayerMatchInfo(address account, uint16 _matchSelected) public view returns (uint256, uint16, uint16, uint){ Bet storage targetBet = playerInfo[account].bets[_matchSelected]; return ( targetBet.amountBet, targetBet.matchSelected, targetBet.resultSelected, playerInfo[account].numFunders ); }
补充说明
- 若要避免查询未参与的比赛返回空值,可在查询逻辑中增加
targetBet.amountBet > 0的存在性校验,也可以自定义错误抛出 - 新增投注的逻辑需要同步调整,写入投注时要以对应的
matchSelected作为bets映射的键,保证数据存储正确
内容的提问来源于stack exchange,提问作者Lloyd Ramos
相关产品推荐
相关产品推荐

