One-to-many relation data implementation

I would like to implement a one-to-many data structure but from what I read a classic key to array solution is not possible, I have also thought about having a nested StorageVec which however I am not sure is the best way. Would anyoe know a better workaround?

Hi again @timotejGerzelj this should be possible try this! Additionally take a look at this forum post which I think might be helpful for you. Is there a way to assign StorageVec inside a struct and then the struct will be used in maps.


use std::storage::storage_vec::*;

storage {
    map: StorageMap<Address, StorageVec<u64>> = StorageMap {},
}

...

toolchain version I’m running

active toolchain
-----------------
latest-aarch64-apple-darwin (default)
  forc : 0.42.0
    - forc-client
      - forc-deploy : 0.42.0
      - forc-run : 0.42.0
    - forc-doc : 0.42.0
    - forc-explore : 0.28.1
    - forc-fmt : 0.42.0
    - forc-index : 0.17.3
    - forc-lsp : 0.42.0
    - forc-tx : 0.42.0
    - forc-wallet : 0.2.3
  fuel-core : 0.18.3
  fuel-indexer : 0.17.3

fuels versions
---------------
forc : 0.43
forc-wallet : 0.43.0

Hi @calldelegation thanks again for a response! The reason I thought this type of data-structure is not possible is because of this post here since I was receiving the same error. Could you show me how to update the StorageVec in StorageMap in this case if you dont mind?

Yes ofcourse! Assuming you’re on the latest version of the toolchain try something like this:

contract;

use std::storage::storage_vec::*;

storage {
    map: StorageMap<u64, StorageVec<u64>> = StorageMap {},
}

abi MyContract {
    #[storage(read, write)]
    fn insert_function(id: u64);

    #[storage(read, write)]
    fn push_function(id: u64);
}

impl MyContract for Contract {
    #[storage(read, write)]
    fn insert_function(id: u64) {
        let nums: StorageVec<u64> =  StorageVec {};
        storage.map.insert(id, nums);
    }

    #[storage(read, write)]
    fn push_function(id: u64) {
        storage.map.get(id).push(100); 
        // Manipulating vecs inside a mapping (.pop(), .remove() etc.)
    }
}

Theres a ton of helper functions other than .push for you to manipulate the StorageVecs here

1 Like

@calldelegation once again thank you! You really are helping me a lot!

1 Like

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.