sailsjs单向关联实现

时间:2016-10-25 04:11:31

标签: sails.js

我按照此链接尝试显示数据

http://sailsjs.org/documentation/concepts/models-and-orm/associations/one-way-association

但是我收到错误"未知栏' shop.building_detail'在'字段列表' "

是风帆错误还是我做错了什么?

我的数据库设计和我的代码在下面

database design

商店模特:

module.exports = {
  autoPK:false,
  attributes : {
  shop_id : {
    primaryKey : true,
    type : 'int',
    unique: true,
    columnName : 'shop_id'
  },
  shop_floor : {
    type : 'string'
  },
  shop_room : {
    type : 'string'
  },
  shop_build : {
    type : 'int',
    foreignKey:'true'
  },
  building_detail : {
    model : 'building'
  }
 }
 };

建筑模型:

module.exports = {
  autoPK:false,
  attributes : {
    build_id : {
      primaryKey : true,
      type : 'int',
      unique: true,
      columnName : 'build_id'
    },
    build_name : {
       type : 'string'
    },
    build_address : {
       type : 'string'
    },
    build_latitude : {
       type : 'float'
    },
    build_longitude : {
       type : 'float'
    },
    build_visit_count : {
       type : 'int'
    },
    build_status : {
       type : 'string'
    },
    build_status_last_update_time : {
       type : 'time'
    }
  }
  };

1 个答案:

答案 0 :(得分:0)

使用您的数据库设计,您的Shop模型可能如下所示:

<强> Shop.js

module.exports = {
  autoPK:false,
  attributes : {
    shop_id : {
      primaryKey : true,
      type : 'int',
      unique: true,
      columnName : 'shop_id'
    },
    shop_floor : {
      type : 'string'
    },
    shop_room : {
      type : 'string'
    },
    shop_build : {
      model: 'Building'
    }
  }
};

Sails.js自动将shop_buildBuilding模型的主键相关联。

创建商店时,只需将建筑物ID指定为shop_build的值:

Shop.create({
  shop_floor: "Some floor",
  shop_room: "Some room",
  shop_build: 8 // <-- building with build_id 8
})
.exec(function(err, shop) { });

当您执行商店查询时,您可以填充建筑物详细信息:

Shop.find()
.populate('shop_build')
.exec(function(err, shops) {
  // Example result:
  // [{
  //   shop_id: 1,
  //   shop_floor: 'Some floor',
  //   shop_room: 'Some room',
  //   shop_build: {
  //     build_id: 8,
  //     build_name: 'Some building',
  //     ...
  //   }
  // }]
});

有关详细信息,请参阅Waterline documentation on associations