Solidity

如何使用結構屬性進行可靠查詢

  • March 14, 2022

在我解釋有關 mu 問題的任何內容之前,我想放上我的程式碼,以便我可以參考它

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

contract GeoSpatialData{

   uint public SpatialDataCount = 0;
   
   struct GeoData{
       uint id;
       address owner_address;
       string data_name;
       string data_year;
       string data_description;
       string data_img_url;
       string data_url;
       string data_category;
       string data_published_date;
   }

   GeoData[] public geoDatas;

   mapping (uint => GeoData) public geodatas;
   // write function
   function createData(string memory _data_name,address _owner_address,string memory _data_year,string memory  _data_description,string memory _data_image_url,string memory _data_url,string memory _data_published_date,string memory _data_category,uint _id ) public{
       SpatialDataCount++;
       uint used_id = SpatialDataCount+_id;
       geoDatas.push(GeoData({id: used_id,owner_address:_owner_address,data_name:_data_name,data_year:_data_year,data_description:_data_description,data_img_url:_data_image_url,data_url:_data_url,data_category:_data_category,data_published_date:_data_published_date}));
       // geoDatas.push(Ge)
   }
   // read all data  function
   function readData() public{

   }

   // read single data function 
   function readSingle() public{

   }

}

我想創建一個函式來使用我始終唯一的 id 函式讀取單個結構數據,然後我還想創建一個函式,通過該函式我可以讀取整個結構,因為現在以後我想要一個分頁功能我怎樣才能做到這一點

您無法通過單個函式從鏈中讀取無限量的數據,因此無法獲取所有結構。除非您修改自己的節點並允許eth_call能夠使用無限的氣體,否則不會。

如果您需要分頁訪問並且您自己的 id 未排序,您可以執行以下操作:

GeoData[] public geoData;
mapping(uint => uint) idIndexMap; // mapping your id to array index

function getGeoData(uint256 id) public view returns (GeoData memory) {
 uint256 index = idIndexMap[id];
 return geoData[index];
}

function paginatedGetGeoData(uint256 offset, uint256 count) public view returns (GeoData[] memory) {
 GeoData[] memory data = new GeoData[](count);
 for (uint256 i = 0; i < count; i++) {
   data[i] = geoData[offset + i];
 }
 return data;
}

引用自:https://ethereum.stackexchange.com/questions/123768