双向Sails.js上的多对多关联

时间:2015-02-05 14:37:48

标签: javascript orm many-to-many sails.js waterline

我开始使用Sails.js(我是一个绝对的新手),我想创建以下类模型。
我有一个Student和一个SubscriptionList。学生拥有他/她订阅的subscriptionLists的集合,并且SubscriptionList知道订阅它的所有学生。因此,它是双向的多对多关联 我使用这些生成器创建了模型:

sails generate model Student firstName:string lastName:string fileNumber:string career:string regid:string email:email

sails generate model SubscriptionList name:string description:string

由于我不知道如何在Sails中运行迁移(我之前在Rails中做了类似的事情),之后我转到了模型的文件,并添加了这个: / p>

id: {
  type: 'integer',
  primaryKey: true,
  autoIncrement: true
},

subscriptionLists:{
  collection: "subscriptionLists",
  via: "students"
}

Student模型,并且:

id: {
  type: 'integer',
  primaryKey: true,
  autoIncrement: true
},

students:{
  collection: "students",
  via: "subscriptionLists"
}

SubscriptionList模型,然后从控制台运行sails lift。我收到了这个错误:

Error: Collection student has an attribute named subscriptionLists that is pointing to a collection named subscriptionlists which doesn't exist. You must  first create the subscriptionlists collection.

这是有道理的,因为我试图一次创建关系的两端(根据我的理解)。
那么,如何在Sails.js中创建双向多对多关系而不通过中间实体(我的意思是,只是使用常规的交叉表)?

任何帮助都将受到高度赞赏 最好的问候。

1 个答案:

答案 0 :(得分:1)

在sails / waterline中创建多对多关系时,会为您构建连接表。你的问题是一个错字。您指定的集合需要与其指向的模型的模型名称相匹配。你有多元化你的。需要像这样:

学生:

id: {
  type: 'integer',
  primaryKey: true,
  autoIncrement: true
},

subscriptionLists:{
  collection: "subscriptionList", // match model name here
  via: "students", // match attribute name on other model
  dominant: true // dominant side
}

SubscriptionList:

id: {
  type: 'integer',
  primaryKey: true,
  autoIncrement: true
},

students:{
  collection: "student", // match model name
  via: "subscriptionLists" // match attribute name
}

See the docs

相关问题