【问题标题】:Sails js One-to-Many Relationship with custom column namesSails js与自定义列名的一对多关系
【发布时间】:2016-05-30 01:30:47
【问题描述】:

在这里遇到了 Sails Js 的严重问题。 所以,我有如下所述的一对多关系(取自官方风帆documentation):

// myApp/api/models/User.js
// A user may have many pets
module.exports = {
  attributes: {
    firstName: {
      type: 'string',
      columnName: "first_name"
    },
    lastName: {
      type: 'string',
      columnName: "last_name"
    },

    // Add a reference to Pets
    pets: {
      collection: 'pet',
      via: 'owner'
    }
  }
};

和依赖模型:

// myApp/api/models/Pet.js
// A pet may only belong to a single user
module.exports = {
  attributes: {
    breed: {
      type: 'string'
      //column name will be 'breed' by default
    },
    typeProperty: {
      type: 'string',
      columnName: "type_property"
    },
    nameProperty: {
      type: 'string',
      columnName: "name_property"
    },

    // Add a reference to User
    owner: {
      model: 'user'
    }
  }
};

当我在以下查询中调用代码时

User.find()
.populate('pets')
.exec(function(err, users) {
  if(err) // handle error

  // The users object would look something like the following
   [{
     id: 123,
     firstName: 'Foo',
     lastName: 'Bar',
     pets: [{
       id: 1,
       // !! Only this property is loaded !!
       breed: 'labrador',
       // !! This property is NOT loaded !!
       typeProperty: undefined,
       // !! This property is NOT loaded !!
       nameProperty: undefined,
       user: 123
     }]
   }]
});

基本上,似乎sails(具体来说是水线)没有映射回属性,这些属性指定了自定义“columName”并且与属性名称不同(例如“typeProperty”存储在type_property 列中)。

有人遇到过这种问题吗?

【问题讨论】:

    标签: sails.js waterline


    【解决方案1】:

    事实上,我遇到了这个问题。属性“columnName”不起作用。似乎 Sails 并没有将此属性优先于其模型的约定命名。

    尝试将模型属性名称更改为与您的数据库属性相同。

    type_property: {
      type: 'string'
    },
    

    这应该使您的属性被填充。在这里工作。

    当相关属性是外键时,列名可以正常工作。

    【讨论】:

    • 我希望我的代码可读,并且不想在我的代码中重新命名字段。现在我通过编写自定义承诺解决了这个问题,它的作用类似于.populate("collectionName"),但优先考虑列名字段。无论如何,这只是部分解决方案。
    猜你喜欢
    • 1970-01-01
    • 2019-02-09
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 2021-12-26
    相关资源
    最近更新 更多