【问题标题】:Populating one to many relationship in sails js without using primary key在sails js中填充一对多关系而不使用主键
【发布时间】:2016-08-30 08:53:17
【问题描述】:

sails/waterline 文档中的每个一对多示例代码都假定主键是两个模型之间的关联(我认为)。

http://sailsjs.org/documentation/concepts/models-and-orm/associations/one-to-many

但是我的模型有一个引用列,该列引用了一些类似于

的其他值
User
{ 
    id (primary): <int>
    email: <string>
} 

recordings
{
    id (primary): <int>
    email: <that email from user>
}

atm 我正在尝试

userModel.js
{
   attributes: {
      email: {
         type: 'string',
            size: 255,
            unique: true
         },
      },
      queries: { 
        columnName: 'email',
        model: 'recordings'
      }
      .....
   }
}

recordingsModel.js
{
   attributes: {
      email: {
         type: 'string',
            size: 255,
         },
      },
      queries: { 
        model: 'user'
      }
      .....
   }
}

在控制器中

sails.models.user
     .find()
     .populate('queries')
     .exec(function (err, results) {

 });

但我得到了错误 :ER_BAD_FIELD_ERROR:“字段列表”中的未知列“__queries.queries”

有没有人对水线中的一对多关系有很好的教程,因为那里的文档非常糟糕,所以我觉得我只是不了解如何设计模型。

【问题讨论】:

  • 在recordingsModel中你有queries属性并且thic列不存在。尝试删除它。

标签: mysql node.js sails.js waterline


【解决方案1】:

据我所知,您想要的是能够设置您的 userModelrecordingsModel 模型,这样,通过为 email 提供特定值的录音,它将自动与任何共享该电子邮件的用户。这不是 Waterline(Sails ORM)支持的东西。

相反,您最好的选择是按照文档中的说明设置模型:

// userModel.js
{
   attributes: {
      email: {
         type: 'string',
            size: 255,
            unique: true
         },
      },
      recordings: { 
        collection: 'recordingsModel',
        via: 'user'
      }
      .....
   }
}

// recordingsModel.js
{
   attributes: {
      email: {
         type: 'string',
            size: 255,
         },
      },
      user: { 
        model: 'userModel'
      }
   }
}

我的猜测是,您正试图避免必须查找用户 ID 才能将新记录与其关联。如果您将email 设为userModel 的主键,则可以执行此操作;然后当你创建一个新的录音时,你可以将它的user 设置为一个电子邮件地址,瞧:这两个是链接的。

【讨论】:

  • 不幸的是,由于其他系统依赖于它,因此我在预先存在的数据库之上进行了调整,我不会改变。不幸的是,sails 似乎比我希望的更固执己见。因此,可能会丢弃传统 mysql 连接的水线。
  • 您也可以随时使用 .query 从 Waterline 进行自定义 SQL 查询。
  • 是的,但是使用水线有什么意义呢?不幸的是,我越来越多地为每个端点这样做。
猜你喜欢
  • 2014-03-07
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 2015-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多