0

I have a question about how I should design my contract to achieve the following: I want to create products identifiers (can be struct or string) something like: "product#123abc". Then I want to map a struct to it (in my case this struct holds location information) Example:

struct Location {
    string city;
    string street;
    uint time;}

And finally I want to map multiple different location structs to my product so that I can call it like this:

function viewLocation(uint _productID, uint _location) public returns(struct){
    return Product[_productID].Location[_location].city;
}

Would it also be possible to just call the productID and show me all mapped locations to it? Something like this:

function viewLocation(uint _productID) public returns(array){
    return Product[_productID].Location;
}

If it doesn't work like I think about it, how would a workaround look like? I hope you can help me :)

1 Answer 1

1

It is possible to do something like this:

struct Location {
    string city;
    string street;
    uint time;
}

struct Product {
    uint id;
    string name;
    mapping (uint => Location) locations;
}

mapping (uint => Product) products;

Then the implementations will be like:

function viewLocation(uint _productID, uint _location) public returns(struct memory Location){
    return products[_productID].locations[_location];
}

Unfortunately plain mappings cannot be iterated. But it is possible to combine in a more complex structure that can be iterated, see this for details and an implementation https://ethereum.stackexchange.com/a/13168.

Another alternative is to keep separated locations and products. And keep an array of location ids:

struct Product {
    uint id;
    string name;
    uint[] locations;
}

mapping (uint => Product) products;

mapping (uint => Location) locations;

The viewLocation will be more complex:

function viewLocation(uint _productID, uint _location) public returns(struct memory Location){
    // Check if _location is in return products[_productID]
    // Return locations[_location] if it is present
    // Fail otherwise
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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