从 Solidity 中的嵌套映射中获取所有项目

Get all Items from nested mapping in Solidity

    // SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";

contract DgramMap is ERC721URIStorage {
    struct TokenDetails {
        string src;
        uint256 sell_price;
        string uniqueId;
    }

    mapping(address => mapping(uint256 => TokenDetails)) public userStructs;

    constructor(address payable _admin) ERC721("Dgram Token", "DT") {
    }

    function add(uint256 _id, address _user) public returns (uint256) {
        TokenDetails memory _tokenDetails = TokenDetails(
            "abc.com",
            12,
            "abcs1234"
        );
        userStructs[_user][_id] =  _tokenDetails;
        return _id;
    } 

    function deleteMap(uint256 _tokenId, address _user) public returns (uint256) {
        delete userStructs[_user][_tokenId];
        return _tokenId;
    } 

    function getItems(address _u) public view returns (TokenDetails memory) {

        // Here I want to return hall TokenDetails[_u]
        return TokenDetails[_u];
    }

}

如何从GetItems获取TokenDetails[_u]大厅??我也不能在这里使用长度。建议任何替代方法(如果有)。 我想要这种类型的结构 [ { keyname: {} }].

您可以在映射中嵌套存储数组,而不是嵌套映射,如下所示:

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

contract MappingsC {
    struct Item {
        uint groupId;
        uint itemId;
    }
    
    mapping(uint => Item[]) private items;
    
    function setItem(uint groupId, uint itemId) public {
        items[groupId].push(Item(groupId, itemId));
    }

    function getItem(uint groupId, uint itemId) public view returns (Item memory) {
        return items[groupId][itemId];
    }
    
    function getItems(uint groupId) public view returns (Item[] memory) {
        return items[groupId];
    }
}

这样,您可以通过将 groupIditemId 传递给 getItem(...) 来单独 return 每个项目,并且仍然能够 return 一个完整的嵌套存储数组,只需将 groupId 传递给 getItems(...)。这与映射不同,因为数组是可迭代的。