Insert Data into a Multi-Index Table
Overview
This guide provides instructions for inserting data into a multi-index table.
Prerequisites
- Before proceeding, ensure that you have completed the Getting Started section and that you have followed the Getting Started Documentation Diagram.
- This page assumes you are familiar with Smart Contract Basics.
- A multi-index
testtab
table instance which storesuser
objects indexed by the primary key which is of typesysio::name
. Consult the section How to instantiate a multi-index table to learn how to set it up.
Steps
Complete the following steps to insert a user object in the testtab
multi-index table:
1. Verify If the User Already Exists
Use the multi-index table iterator to find out if the user object already exists. The targeted user is searched based on its account name.
contract.cpp
[[sysio::action]] void multi_index_example::set(name user) {
// check if the user already exists
auto itr = testtab.find(user.value);
}
2. Insert the User If Not Found in Table
Use the emplace
method to make the insertion if the user object is not already in the multi-index table. Otherwise print an informational message.
contract.cpp
[[sysio::action]] void multi_index_example::set(name user) {
// check if the user already exists
auto itr = testtab.find(user.value);
if (itr == testtab.end()) {
testtab.emplace(_self, [&](auto& u) {
u.test_primary = user;
u.secondary = "second"_n;
u.datum = 0;
});
} else {
printf("User already exists.");
}
}
info
A full example project demonstrating the instantiation and usage of multi-index tables can be found in the multi_index example
project.
Reference
Relevant classes and methods:
Next Steps
- Iterate and retrieve newly inserted data from the multi-index table.