0

Hey guys I'm a bit new to solidity,

In the offical example of ethereum they handle the relations with a map :

Pizza[] public pizzas;

// Mapping from owner to id of Pizza
mapping(uint256 => address) public pizzaToOwner;

So if you want to know the Pizzas of an user you have to iterate over the whole list

function getPizzasByOwner(address _owner)
    public
    view
    returns (uint256[] memory)
{
    uint256[] memory result = new uint256[](ownerPizzaCount[_owner]);
    uint256 counter = 0;
    for (uint256 i = 0; i < pizzas.length; i++) {
        if (pizzaToOwner[i] == _owner) {
            result[counter] = i;
            counter++;
        }
    }
    return result;
}

as far I understand : iterating over maps/arrays is all about gas, so this approac would be to thick? .

I created a similar case with a struct ( on example with colors ) that handles the relations like that

struct Holder
{
    address id;
    string name;
    Color[] colors; // tryed out without and relation map
}

mapping(address => Holder) public holders;

so getting all colors looks like this

function getColorsByAddress(address _address) public view 
returns (uint256[] memory)
{
    uint256[] memory result = new uint256[](holders[_address].colors.length);

    for (uint256 i = 0; i < holders[_address].colors.length; i++) {

            result[i] = holders[_address].colors[i].id;
    }
    
    return result;
}

the full code example would be here https://gist.github.com/DomEscobar/d35bbc65d8c8cdebf5cdaa1dd338161c

The question now : What is the best practise to handle relations is there a better way?

Your Answer

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

Browse other questions tagged or ask your own question.