0

Here is defined a sample table with four fields, two of them (account and type) I am going to use in my compound search:

struct [[eosio::table]] total
{
   uint64_t id;
   uint64_t account;
   uint64_t type;
   uint64_t count;

   uint64_t primary_key() const { return id; }
   uint64_t account_key() const { return account; }
   uint64_t type_key() const { return type; }
   uint128_t group_key() const { return combine_ids(account, type); }
};
typedef eosio::multi_index<"totals"_n, total,
    eosio::indexed_by<"groupkey"_n, eosio::const_mem_fun<total, uint128_t, &total::group_key>>> totals;
totals totalsTable;

We have to implement a function, building the search index we are going to use in our compound search:

static uint128_t combine_ids(const uint64_t &x, const uint64_t &y)
{
   return (uint128_t{x} << 64) | y;
}

And finally the actual searching and sample implementation of add/update functionality:

// search by group of fields (account + type)
auto totals_index = totalsTable.get_index<name("groupkey")>();
auto group_id = combine_ids(account.value, type);
auto itr = totals_index.find(group_id);

if (itr == totals_index.end())
{
   // add new record
   totalsTable.emplace(_self, [&](auto &r)
   {
      r.id = totalsTable.available_primary_key();
      r.account = account.value;
      r.plastic_type = type;
   });
}
else
{
   // update existing record
   totals_index.modify(itr, _self, [&](auto &r)
   {
      r.count += count;
   });
}
  • 1
    Unable to find question. Please describe the problem/question in question's section and answer in answer's section. – Farhan-TroonTechnologies Jul 8 at 13:15

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.