[Ethereum] How to create complex array relationships in solidity

arrayscontract-developmentsolidity

Hello I'm trying to work out how to create complex relationships in Solidity.

In this example a customer will place an order using a function with arguments, however it cannot be for any combination of shops, types, and products, the relationship must already be established.

In a normal relational database the foreign keys would ensure the relationship was good, and I think in Solidity this is the case with mappings, but I'm not sure how this could be applied:

struct ShopName {
    string name; // ShopA, ShopB, ShopC
}

// Each shop can have one or more types 
struct ShopType {
    string type; // market, brick, online 
}

// each type can have one or more products
struct Product {
    string productCode;
    uint unitPrice;
}

struct SalesOrders {
    address customer;
    uint qty;
    string status; // paid, unpaid
}

So I am imagining a transaction something like this:

function placeOrder(string _shopName, string _shopType, string _productCode, uint _qty) {
    ...
}

In this example the ShopName ShopType and Product must have an established set of related values, and when an order is placed only those related values can be allowed.

But somehow I think I have a got totally lost because I don't know how to think about this problem, let alone how to access the data.

I have seen the example in readthedocs but I am confused about putting this into practice. Can someone give me some direction please?

Best Answer

This could be useful, from https://dappsforbeginners.wordpress.com/tutorials/typing-and-your-contracts-storage/

We can also include mappings as data types within another mapping:

contract rainbowCoin {
mapping (address => mapping (uint => uint)) balances;
function rainbowCoin() {
    balances[msg.sender][0] = 10000; ///red coin
    balances[msg.sender][1] = 10000; ///orange coin
    balances[msg.sender][2] = 10000; ///yellow coin
    balances[msg.sender][3] = 10000; ///green coin
    balances[msg.sender][4] = 10000; ///blue coin
    balances[msg.sender][5] = 10000; ///indigo coin
    balances[msg.sender][6] = 10000; ///violet coin
}
function sendCoin(address receiver, uint amount, uint coin) returns(bool successful) {
    if (balances[msg.sender][coin] < amount) return false;
    balances[msg.sender][coin] -= amount;
    balances[receiver][coin] += amount;
    return true;
}

}

Think about the potentials of this:

It is also possible to place mappings inside of structs, and place structs inside mappings – in fact the only data type that you cannot place inside a struct or a mapping is itself.

Could you give us a feedback about how many mappings you could successfully implement into each other? I never tried this out :)

Related Topic