BookhshelfJS:实现一对一的关系

时间:2016-02-10 21:11:36

标签: javascript node.js relational-database bookshelf.js

我有两个表,UserAddress。我的表User有两种方法:

shippingAddress: function() {
    var Address = require(appRoot + '/config/db').model('Address');
    return this.belongsTo(Address, 'shipping_address_id');
},

billingAddress: function() {
    var Address = require(appRoot + '/config/db').model('Address');
    return this.belongsTo(Address, 'billing_address_id');
}

如何附上Address来说出shippingAddress?我尝试了以下方法:

new Address(addressQuery)
    .fetch()
    .then(function (address) {
        new User(userQuery)
            .fetch()
            .then(function (user) {
                // Nothing here works
                // I tried the following:
                user.shippingAddress().attach(address); // Attach is not defined
                user.shippingAddress().sync(address);   // Nothing happens
                user.shippingAddress().set(address);    // Nothing happens
                user.save();
            });
    });

我唯一能做的就是:

user.attributes.shipping_address_id = address.id;
user.save();

这不是一个非常优雅的解决方案。我做错了什么?

1 个答案:

答案 0 :(得分:0)

首先,使用“withRelated”

设置关系列表
html,body,.carousel,.carousel a.item { height: 100%; }
.carousel a.item {
  height: 100%;
  padding-top: 100px;
  position: relative;
  overflow: hidden;
  width: 25%;
  float: left;
}
.rotate {
  white-space: nowrap;
  position: absolute;
  bottom: 50px;
  left: 100%;
  transform-origin: left bottom;
  transform: rotate(-90deg);
}
.carousel a.item h1 {
  color: #fff;
}
.bg-image {
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
}

然后你就可以:

new User(userQuery)
        .fetch({
            withRelated:['shippingAddress']
        })
        .then(function (user) {

确保shippingAddress()不是用户模型中的“静态”功能