【问题标题】:Bookshelf.js - hasOne relationship not working wellBookshelf.js - hasOne 关系不正常
【发布时间】:2015-02-24 12:47:18
【问题描述】:

我对 bookshelf.js 还很陌生,所以请多多包涵。

由于我正在学习,我正在使用 MySQL 并且具有非常简单的结构。即,两个实体,具有一个辅助密钥。这是我的结构:

CREATE TABLE IF NOT EXISTS `city` (
  `city_id` int(11) NOT NULL,
  `code` int(11) NOT NULL,
  `name` varchar(255) COLLATE utf8_bin NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

CREATE TABLE IF NOT EXISTS `people` (
  `people_id` int(11) NOT NULL,
  `city_id` int(11) NOT NULL,
  `name` varchar(255) COLLATE utf8_bin NOT NULL,
  `age` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

ALTER TABLE `city`
  ADD PRIMARY KEY (`city_id`);

ALTER TABLE `people`
  ADD PRIMARY KEY (`people_id`), ADD KEY `city_id` (`city_id`);

ALTER TABLE `people`
ADD CONSTRAINT `people_ibfk_1` FOREIGN KEY (`city_id`) REFERENCES `city` (`city_id`);

这是我在 expressjs 中的代码,使用书架:

var City = bookshelf.Model.extend({
    tableName: 'city'
});

var User = bookshelf.Model.extend({
  tableName: 'people',
  city: function(){
    return this.hasOne(City, 'city_id');
  }
});

这是我如何运行查询的示例代码:

new User().where({people_id: req.params.id })
.city()
.fetch()
.then(function(user){
    res.send(user.toJSON());
})
.catch(function(error){
    res.send(error);
});

但是,当我运行应用程序时,我只得到一个空的 json:

{}

我在书架中启用了调试模式,这是它尝试执行的查询:

 { __cid: '__cid1',
   method: 'select',
   options: undefined,
   bindings: [ undefined, 1 ],
   sql: 'select `city`.* from `city` where `city`.`city_id` = ? limit ?' }

现在我已经说过了,我是书架新手。但这没有任何意义;为什么不将 city.city_id 与 person.city_id (外键)进行比较?

感谢您的宝贵时间和回答!

【问题讨论】:

    标签: javascript mysql node.js express bookshelf.js


    【解决方案1】:

    您可以通过以下操作使其正常工作:

    1.) 将主键主键重命名为id。主键应该是city.id,而不是city.city_id

    2.) 将用户定义中的关系更改为return this.belongsTo(City);

    3.) 你可以通过new User({id: 1}).fetch({ withRelated: ['city'] });访问城市

    【讨论】:

    猜你喜欢
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 2021-08-15
    • 2017-04-21
    相关资源
    最近更新 更多