如何在航行中使用多对多

时间:2019-05-06 16:07:31

标签: node.js sails.js

我使用Sails v0.12。下面的代码不起作用。

user.pets.add({ breed: 'labrador', type: 'dog', name: 'fido' });

我无法在数据库中添加宠物记录。

User.findOne(1).exec(function (err, user) {
 if (err) // handle error

 // Queue up a new pet to be added and a record to be created in the join table
 user.pets.add({ breed: 'labrador', type: 'dog', name: 'fido' });
 console.log(user);
 // Save the user, creating the new pet and associations in the join table
 user.save(function (err, rs) {
   console.log(err);
   console.log(rs);
 });
});
// myApp/api/models/User.js
// A user may have many pets
module.exports = {
    attributes: {
      firstName: {
        type: 'string'
      },
      lastName: {
        type: 'string'
      },

      // Add a reference to Pet
      pets: {
        collection: 'pet',
        via: 'owners',
        dominant: true
      }
    }
  };
// myApp/api/models/Pet.js
// A pet may have many owners
module.exports = {
    attributes: {
      breed: {
        type: 'string'
      },
      type: {
        type: 'string'
      },
      name: {
        type: 'string'
      },

      // Add a reference to User
      owners: {
        collection: 'user',
        via: 'pets'
      }
    }
  };

0 个答案:

没有答案