Search code examples
structmappingblockchainethereumsolidity

Is the mapping in solidity of one key on multiple structs of same type possible?


I am trying to map one address on multiple structs of same type, which belongs to the same address. How can I do this, if I want to choose any of the "stored" structs for one address on request afterwards?

I created a struct called Prescription, and a mapping with the patients address. So what I really want is to map the patients address to several Prescription-structs.

struct Prescription {
    address patients_address;
    string medicament;
    string dosage_form;
    uint amount;
    uint date;
}

mapping (address => Prescription) ownerOfPrescription;

address [] public patients;

function createPrescription(address patients_address, string medicament, string dosage_form, uint amount, uint date) public restricted {
    var newPrescription = ownerOfPrescription[patients_address];

    newPrescription.medicament = medicament;
    newPrescription.dosage_form = dosage_form;
    newPrescription.amount = amount;
    newPrescription.date = date;

    patients.push(patients_address) -1;
}

function getPre(address _address)view public returns (string, string, uint, uint){ 
    return( 
        ownerOfPrescription[_address].medicament, 
        ownerOfPrescription[_address].dosage_form, 
        ownerOfPrescription[_address].amount, 
        ownerOfPrescription[_address].date);
}

Now I would have a function, where I can call all written Prescriptions for one patient. Actually I am able to call only the last written prescription for one address.


Solution

  • Sure, the value type of a mapping can be an array:

    // map to an array
    mapping (address => Prescription[]) ownerOfPrescription;
    
    function createPrescription(...) ... {
         // add to the end of the array
         ownerOfPrescription[patients_address].push(Prescription({
             medicament: medicament,
             ...
         });
    
         patients.push(patients_address);
    }