waterline-model.create-primaryKey

问题描述 投票:4回答:3

我有以下型号的主键ID:

attributes: {
   id: {
      type: 'integer',
      autoIncrement: true,
      primaryKey: true,
      unique: true
   },
    name: {
      type: 'string',
      unique: true,
      required: true
   },
}

我正在如下创建模型:

var model = {
     id: undefined,
     name: 'name',
};

waterlinemodel.create(model).exec(function(error,result){});

但是它抛出以下错误:错误(E_UNKNOWN)遇到意外错误]详细信息:错误:“ id”列中的空值违反了非空约束

作为'id'是主键,吃水线不应查看'id'属性的值是什么。

如何解决此错误?我不想删除'id',因为我已经为模型创建了值对象,并且包含了模型的所有属性。我根据需要设置值对象属性。我不需要为创建设置id属性。

database node.js sails.js waterline
3个回答
1
投票

我遇到了完全相同的问题,尤其是配置为使用postgresql的模型。将其设置为磁盘或内存后,将创建资源,但使用postgresql时,不会创建具有非null约束错误的资源。

无论是否设置autoPK: true,都不会设置ID。即使使用autoPK:false在模型上设置id属性也不起作用。


0
投票

正如文档所说:

Will set the primary key of the record. This should be used when autoPK is set to false.

attributes: {
  uuid: {
    type: 'string',
    primaryKey: true,
    required: true
  }
}

您需要在模型上设置autoPK : false

指向文档的链接:https://github.com/balderdashy/waterline-docs/blob/master/models.md#primarykey


0
投票

2019回答

[jaumard的文档链接现在出现404错误,但我认为自2015年以来情况可能有所改变...

Sails.js具有在config/models.js中定义的基本属性,在新生成的项目中看起来像这样:

attributes: {
  createdAt: { type: 'number', autoCreatedAt: true, },
  updatedAt: { type: 'number', autoUpdatedAt: true, },
  id: { type: 'number', autoIncrement: true, },
}

另外,默认的primaryKey设置为id。如果要覆盖它,则需要在完整模型定义中明确指定新的primaryKey。例如,如果您想将name设置为primaryKey,则可以使用以下代码:

module.exports = {
  primaryKey: 'name',
  attributes: {
    name: {
      type: 'string',
      unique: true,
      required: true
    },
    // ...
  },
}

[注意,我将primaryKey放在attributes之外。这个很重要。您的primaryKey也将需要uniquerequired约束。

此外,如果要禁用id列以使其不提交给数据库,则必须将id替换为值false,但是必须定义另一个primaryKey ],否则在启动应用程序时会出现错误。问题中显示的错误可能与模型将id明确定义为undefined的事实直接相关。如何禁用id的示例如下所示:

module.exports = {
  primaryKey: 'name',
  attributes: {
    id: false,
    name: {
      type: 'string',
      unique: true,
      required: true
    },
    // ...
  },
}
© www.soinside.com 2019 - 2024. All rights reserved.