1

If id(Eg:1) field in structure is not unique and different names are mapped with same id=1. Can all names mapped with id=1 could be fetched from blockchain?

pragma solidity ^0.4.4;

 contract Register{

 struct Details{
  bytes id;
  string name;

  }
 mapping (bytes => Details) DetailsTable;

 function saveBondToBC(bytes id,string name) 
 payable returns(bool success){

DetailsTable[id].id = id;
DetailsTable[id].name = name;
return true;
}

function getAllNames(bytes id) return (string){
DetailsTable[id].name; //Return latest 'name' written
 }     
2

mapping are unique (or many-to-one relationship in relational database jargon). For example if id 123 is mapped to name Vitalik. Id 123 can only lead to Vitalik and no other value ! However others id (e.g. 947) can also point to Vitalik (many-to-one relationship).

If you update the mapping 123 => Vitalik to 123 => Gavin for example, then well obviously the id 123 will be pointing to Gavin and Gavin only.

I am not sure if it is obvious or not but for the sake a clarity, in those lines

DetailsTable[id].id = id;
DetailsTable[id].name = name;

you do not update your mapping at all but only the fields in your structure. Also if your ids are two different values I would find better names. If your id in the struct is the same as the id for the mapping there is no point of storing the id in the struct again (this creates redundancy and will just add overhead for keeping the two values sync).

also you cannot loop over mapping neither knowning which ids have been initialized (all mapping are valid) if you do not keep track of your ids (either in your smart-contract or off-blockchain in a database)

In your smart contract your could create an array for that

bytes[] allMyUniqueIds;

then looping over allMyUniqueIds will return you all your Details struct

2
  • Yes, I could store ID in an array.But what I need is one-to-many relationship.Is that possible in any way?
    – angelmaria
    Feb 8 '18 at 4:43
  • Yes it's possible. I wrote an example some days ago. Follow this link ethereum.stackexchange.com/questions/37988/… and there is plenty of example out there :)
    – salanfe
    Feb 8 '18 at 7:47
1

Thanks, this one worked for me :)

struct IdStruct{

bytes12[] structArray; 
}

mapping(string => IdStruct) idStructs;

function appendNames(string id, bytes12 name) payable returns (bool success){ 
 idStructs[id].structArray.push(name); 
} 

function getName(string id) returns(bytes12[]){ 
return idStructs[id].structArray; 
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.