Access nested mapping solidity

Viewed 965

NOTE: I asked this question a few days ago while I had solidity 0.7.0. Now I am using solc 0.8.0. With the new ABI V2 encoding, this should be possible. However, I still got stuck.

NOTE2: I know I can write a getter to get a specific review. However, I am aware of gas costs and I need to get all the ratings in one go to compute averages, so I don't think it is feasible.

Suppose I have this data structure layout:

    struct ReviewStruct {
        string rating;
        ...
    }

    struct Restaurant {
        ...
        uint reviewCount;
        mapping(uint => ReviewStruct) reviews;
    }

    uint public restaurantCount = 0;
    mapping(uint => Restaurant) public restaurants;

Then, when I'm trying to access stuff in my JS app, it works, but not if I'm trying to access an actual review:

const restaurantCount = await review.methods.restaurantCount().call() // works
const restaurant = await review.methods.restaurants(2).call() // works
const reviewObj = await review.methods.restaurants(2).reviews(0).call() // throws an error

How do I access a mapping that is inside of a mapping (both are related to structs)?

1 Answers

Your reviews mapping is defined inside your Restaurant struct, thats why you can't access it, you need to access a restartant first to access its reviews.

For example:

const restaurantCount = await review.methods.restaurantCount().call()
const restaurant = await review.methods.restaurants(2).call()

for(let i = 0; i > restaurant.reviewCount; i++){
     let reviewObj = restaurant.reviews[i];
     console.log(reviewObj);
};
Related