【问题标题】:sailsjs one-way-association implementationsailsjs 单向关联实现
【发布时间】:2016-10-25 04:11:30
【问题描述】:

我点击此链接并尝试显示数据

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'
    }
  }
  };

【问题讨论】:

    标签: sails.js


    【解决方案1】:

    使用您的数据库设计,您的 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

    【讨论】:

    • 如果他想像 shop_build: [8, 9, 10] 那样存储 shop_build 数组怎么办,如何实现呢?谢谢。
    • @noyruto88 然后您将使用collection 属性定义一对多或多对多关联。有关更多信息,请参阅文档:sailsjs.com/documentation/concepts/models-and-orm/associations 及其子页面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多