让我们来谈谈 sailsJS 的 One-to-Many

User 对应多个 Car , 对应多个 BankCard,对应多个 XXX,应该怎样建模?
很遗憾,官方文档并没有解释得那么详细,所以我们要自己去验证一下。
首先,创建模型

// myApp/api/models/User.js
module.exports = {

  attributes: {
    firstName: {
      type: 'string'
    },
    lastName: {
      type: 'string'
    },
    cars: {
      collection: 'car',
      via: 'owner'//owner是外键,你完全可以自定义
    },
    //注意这里,官方文档中并没有这样写,这是我们需要验证的地方
    bankCards: {
      collection: 'bankcard',
      via: 'owner'
    }
  }
};
// myApp/api/models/Car.js
module.exports = {

  attributes: {
    name: {
      type: 'string'
    },
    owner: {
      model: 'user'
    }
  }
};
// myApp/api/models/BankCard.js
module.exports = {

  attributes: {
    name: {
      type: 'string'
    },
    number: {
      type: 'string'
    },
    owner: {
      model: 'user'
    }
  }
};

然后,分别添加数据

http://localhost:1337/user/create?firstName=li&lastName=sa
http://localhost:1337/car/create?name=Rolls-Royce&owner=1
http://localhost:1337/bankcard/create?name=%E4%B8%AD%E5%9B%BD%E9%93%B6%E8%A1%8C&number=123456789&owner=1

取出数据

http://localhost:1337/user
http://localhost:1337/car
http://localhost:1337/bankcard

这里写图片描述

2016年12月5日 重庆-传说

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值