A primary key is required when defining a multi index table structure. See the following example:
- Include the
eosio.hpp
header and declare theeosio
namespace usage
#include <eosio/eosio.hpp>
using namespace eosio;
- Define the data structure for the multi index table
struct [[eosio::table]] test_table {
};
- Add to the data structure the fields which define the multi index table
// the data structure which defines each row of the table
struct [[eosio::table]] test_table {
+ // this field stores a name for each row of the multi index table
+ name test_primary;
+ // additional data stored in table row, e.g. an uint64_t type data
+ uint64_t datum;
};
- Add the definition of the primary index for the multi index table. The primary index type must be uint64_t and must be unique
// the data structure which defines each row of the table
struct [[eosio::table]] test_table {
// this field stores a name for each row of the multi index table
name test_primary;
// additional data stored in table row
uint64_t datum;
+ // mandatory definition for primary key getter
+ uint64_t primary_key( ) const { return test_primary.value; }
};
- For ease of use, define a type alias
test_tables
based on theeosio::multi_index
template type, parametarized with a random name"testtaba"
and thetest_table
data structure defined above
// the data structure which defines each row of the table
struct [[eosio::table]] test_table {
// this field stores a name for each row of the multi index table
name test_primary;
// additional data stored in table row
uint64_t datum;
// mandatory definition for primary key getter
uint64_t primary_key( ) const { return test_primary.value; }
};
+ typedef eosio::multi_index<"testtaba"_n, test_table> test_tables;
Declare the multi index table as a data member of type test_tables
, as defined above.
// the data structure which defines each row of the table
struct [[eosio::table]] test_table {
// this field stores a name for each row of the multi index table
name test_primary;
// additional data stored in table row
uint64_t datum;
// mandatory definition for primary key getter
uint64_t primary_key( ) const { return test_primary.value; }
};
typedef eosio::multi_index<"testtaba"_n, test_table> test_tables;
+ test_tables testtab;
Now you have instantiated the testtab
as a multi index table which has a primary index defined for its test_primary
data member.