Solidity
如何將結構的實例添加到另一個結構的數組中?
嗨,我對 Solidity 很陌生。我正忙於一個記錄有關牛的各種資訊的項目。
在我下面的程式碼中,我的牛結構有一個 CattleHealth 和 CattleGrowth 數組,它們應該保存執行檢查的記錄。現在在我的 RecordHealth 和 RecordGrowth 函式中,我打算用時間戳記錄資訊並將其作為單個記錄添加到相應的數組中。
但是,我意識到我可能在使用記錄地址時犯了一個大錯誤,因為這會在每次輸入時覆蓋資訊(如果我錯了,請糾正我)。那麼如何添加單獨的記錄並將其連結到正確的奶牛/公牛?
contract WagyuRecordContract { address farmer; struct Cattle { address RFID; string Name; uint256 Weight; string Gender; string Colour; string Breed; uint Age; uint DOB; string Location; bool Parent; string SireName; string DamName; bool Active; bool ForSale; CattleHealth[] HealthRecord; CattleGrowth[] GrowthRecord; CattleMovements[] MovementsRecord; } struct CattleHealth { uint DateRecorded; string BodyCondition; string HealthStatus; string Medication; } struct CattleGrowth { uint DateRecorded; uint256 FoodIntake; uint256 Growth; } struct CattleMovements { string From; string To; } mapping (address => Cattle) public cattle; mapping (address=> CattleHealth) public health; mapping (address=> CattleGrowth) public growth; modifier Farmer() { require(msg.sender == farmer); _; } function addNewCattle(address rfid, string _name, uint _weight, string _gender, string _colour, string _breed, uint _age, uint _dob) Farmer public { cattle[rfid].Name = _name; cattle[rfid].Weight = _weight; cattle[rfid].Gender = _gender; cattle[rfid].Colour = _colour; cattle[rfid].Breed = _breed; cattle[rfid].Age = _age; cattle[rfid].DOB = _dob; } function NewCattleDetails(address rfid, bool _parent, string _location, string _sireName, string _damName, bool _active, bool _forSale) public Farmer { cattle[rfid].Parent = _parent; cattle[rfid].Location =_location; cattle[rfid].SireName = _sireName; cattle[rfid].DamName =_damName; cattle[rfid].Active = _active; cattle[rfid].ForSale = _forSale; } function RecordHealth(address rfid, string _bodyCond, string _healthStat, uint256, string _med) Farmer public { health[rfid].DateRecorded = now; health[rfid].BodyCondition = _bodyCond; health[rfid].HealthStatus = _healthStat; health[rfid].Medication = _med; cattle[rfid].HealthRecord.push(health[rfid]); } function RecordGrowth(address rfid, uint256 _foodIntake, uint256 _growth) Farmer public { growth[rfid].DateRecorded = now; growth[rfid].FoodIntake = _foodIntake; growth[rfid].Growth = _growth; cattle[rfid].GrowthRecord.push(growth[rfid]); } }
是的,你是對的,你只會保留最後的成長和健康記錄。我認為您可以刪除這兩行:
mapping (address=> CattleHealth) public health; mapping (address=> CattleGrowth) public growth;
而是在以下位置創建記錄:
CattleHealth[] HealthRecord; CattleGrowth[] GrowthRecord;
使用
push()
方法。