代码之家  ›  专栏  ›  技术社区  ›  jmm

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

  •  1
  • jmm  · 技术社区  · 11 年前

    我开始使用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中也做过类似的事情),因此之后我转到模型的文件,并添加如下内容:

    id: {
      type: 'integer',
      primaryKey: true,
      autoIncrement: true
    },
    
    subscriptionLists:{
      collection: "subscriptionLists",
      via: "students"
    }
    

    大学生 模型,以及:

    id: {
      type: 'integer',
      primaryKey: true,
      autoIncrement: true
    },
    
    students:{
      collection: "students",
      via: "subscriptionLists"
    }
    

    订阅列表 模型,并运行 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 回复  |  直到 11 年前
        1
  •  1
  •   jmm    11 年前

    当您在帆/水线中创建多对多关系时,将为您构建一个联接表。你的问题是拼写错误。您指定的集合需要与它所指向的模型的模型名称相匹配。您的集合已被复数化。需要这样:

    学生:

    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
    }
    

    订阅列表:

    id: {
      type: 'integer',
      primaryKey: true,
      autoIncrement: true
    },
    
    students:{
      collection: "student", // match model name
      via: "subscriptionLists" // match attribute name
    }
    

    See the docs

    推荐文章