【问题标题】:Sailsjs one-to-many empty resultsSailsjs 一对多空结果
【发布时间】:2017-06-15 08:57:51
【问题描述】:

我是sailsjs 的新手。试图将我的应用程序后端更改为sailsjs。有一个我需要使用的现有数据库。尝试使用一对多关联时出现此空错误:

{
  "Result": [
    {
      "newCars": [],
      "name": 'Someone',
      "id": 1
    }
  ]
}

这些是我拥有的两个示例表的结构:

table user
id  |   name
1   |   Someone  


table new_car
name    |   user_id
Audi    |   1
BMW     |   1   

型号: (我不确定 - 关联、收藏和通过的命名)

//UserController.js
module.exports = {
  tableName: 'user',
  attributes: {
    name: {
      type: 'string'
    },
    newCars: {              //i can name this anything?
      collection: 'newCar',     //should this be new_car (table name)?
      via: 'user'           //this is one-side table name?
    }
  },
  autoCreatedAt: false,
  autoUpdatedAt: false
};


//NewCarController.js
module.exports = {
    tableName: 'new_car',
    attributes: {
        name: {
            type: 'string'
        },
        users: {
            model: 'User'
        }           
    },
    autoCreatedAt: false,
    autoUpdatedAt: false
};

控制器:

Role.find(1).populate('newCars').exec(function (err, result){
    res.json({Result: result});
});

我也添加了一些我在 cmets 中遇到的问题。

【问题讨论】:

    标签: sails.js waterline


    【解决方案1】:

    您需要将collection 名称更改为newcar。在Sails 中,每当在viacollectionmodel 中引用模型时,您都需要使用小写的名称。阅读更多here

    注意

    您需要允许Sails 创建自己的关联表。例如,您需要创建模型UserCar 并让Sails 为您做映射。它是通过在内部创建一个将user_id 映射到car_idUser_Car(不一定是同名)表来完成的。这可以通过使用sails-generate-api 创建两个apis 来完成

    $ sails generate api User

    $ sails generate api Car

    现在你的模型看起来像:

    //User.js
    module.exports = {
    
      attributes: {
        name: 'string',
    
        cars: {
          collection: 'car',
          via: 'user'
        }
      }
    };
    
    // Car.js
    module.exports = {
    
      attributes: {
        name: 'string',
    
        user: {
          model: 'user'
        }
      }
    };
    

    现在您可以通过将HTTP POST 发送至/user 并将汽车发送至/car 来创建User

    要创建关联User=>Car,请将HTTP POST 发送到/user/:id/car/:id

    现在,当您通过GET /user/:id 获取User 的详细信息时,将填充user[:id] 拥有的所有Cars

    【讨论】:

    • 谢谢,但在做出您建议的更改后仍然没有运气。查看我的表结构和您的评论,“via”应该是“user”还是“user_id”。请注意,也尝试将其更改为 user_id,但结果仍然为空:(
    • user_id 字段是由Sails 适配器创建的吗?
    • 不,我的数据库在试用sailsjs 之前就已经存在。用户 (id, name) 和 new_car(name, user_id)
    • 我已经编辑了我的答案,你的表结构应该改变
    • 这只是简化我面临的问题的一个例子。我的实际数据库是遗留的并且很大,不能改变它的结构,因为其他 API 也在访问它。你的意思是有一种方法可以只更新现有的表结构而不改变太多或影响数据吗?有什么想法吗?
    【解决方案2】:

    设法修复它。它可能对像我这样的新手有用。只需要识别主键和外键。

    //at the one side
    id: {
        type: 'integer',
        primaryKey: true
    }
    
    
    //at the many side      
    user: {
        columnName: 'user_id',
        model: 'user'
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 2017-03-27
      • 1970-01-01
      相关资源
      最近更新 更多