Insert data
Overview
This guide provides instructions to insert data into a multi-index table.
Procedure
Complete the following steps to insert an user object in the datatable
multi-index table:
1. Verify If The User Already Exists
Use of the multi-index table iterator to find out if the user object already exists. The targeted user is searched based on its account name.
[[inery::action]] void multi_index_example::set( name user ) {
// check if the user already exists
auto itr = datatable.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.
[[inery::action]] void multi_index_example::set( name user ) {
// check if the user already exists
auto itr = datatable.find(user.value);
+ if ( itr == datatable.end() ) {
+ datatable.emplace( _self, [&]( auto& u ) {
+ u.test_primary = user;
+ u.secondary = "second"_n;
+ u.datum = 0;
+ });
+ }
+ else {
+ printf("User already exists.");
+ }
}
Summary
In conclusion, the above instructions show how to insert data in a multi-index table.