Relation many to many

Hi guys, I have games that a user has many coins (bnb, eth, etc…), User object and Coins Object is a many to many relations,

const user = Moralis.User.current();
const relation = user.relation(‘coiningame’);
relation.add(coins)
user.save()

now, how to i can add a field in relation that a user have coin in game to play, ex user A has 5 coin BNB, 10 coin ETH …

thank for help

1 Like

I see this as a table where you have a column as a pointer to a user (user.id), a column that is the token name and a column that is the token quantity.
and the rows will look like
(user A, BNB, 10)
(user B, ETH, 10)

thank for help, but my problem is I want to use many-to-many relations in moralis, I understand which create a new table will resolve my problem.

a many to many relation doesn’t mean creating another table?

i understand, i just question how I can add a field name is ‘coiningame’ in relation which i do not create a table. ex I want my code is:
const user = Moralis.User.current();
const relation = user.relation(‘coiningame’);
relation.add(coins)
relation.add(‘coiningame’, 10) // i want
user.save(),

but moralis not support above code.

Would this be an acceptable solution?

// creating a simple coin
coin = Moralis.Object.extend("Coin");
bnb_coin = new coin({name: 'BNB'})
eth_coin = new coin({name: 'ETH'})
await bnb_coin.save()
await eth_coin.save()

coin_nr = Moralis.Object.extend("Coin_nr")
coin_nr_1 = new coin_nr({coin: bnb_coin, nr: 10})
coin_nr_2 = new coin_nr({coin: eth_coin, nr: 5})
await coin_nr_1.save()
await coin_nr_2.save()

user = Moralis.User.current();
relation = user.relation('coiningame');
relation.add([coin_nr_1, coin_nr_2])
await user.save()

I create a new collecttion and add two fields ‘userID’ refer to User Object , ‘coinId’ refer to Coin Object. Its ok !

Moralis.Cloud.beforeSave(Moralis.User, async function(request) {

  logger.info('before save user');

  const { object: user }  = request;

  const username = user.get('username');

  const qr = new Moralis.Query('User');

  qr.equalTo('username', username);

  const userClass = await qr.first({useMasterKey: true});

  if(userClass) {

    const Coins = Moralis.Object.extend('Coins');

    const queryCoins = new Moralis.Query(Coins);

    queryCoins.equalTo('status', true);

    const result = await queryCoins.find();

    const CoinGames = Moralis.Object.extend('CoinGames');

      for (let i = 0; i < result.length; i++) {

        let queryCoinGames = new Moralis.Query(CoinGames);

        queryCoinGames.equalTo('userId', userClass);

        queryCoinGames.equalTo('coinId', result[i]);

        let count = await queryCoinGames.count();

        if(count == 0) {

          let coinGames = new CoinGames();

          coinGames.set('userId', userClass);

          coinGames.set('coinId', result[i]);

          coinGames.set('coin', 0);

          coinGames.save();

        }

      }

  }

  {

    logger.info(JSON.stringify(request))

  }

});