简体   繁体   English

Bookshelf.js-hasOne关系无法正常工作

[英]Bookshelf.js - hasOne relationship not working well

I'm fairly new to bookshelf.js so please bear with me. 我是bookshelf.js的新手,所以请多多包涵。

Since I'm learning, I'm using MySQL and have a really simple structure. 自学习以来,我一直在使用MySQL,并且结构非常简单。 Namely, two entities, with one secondary key. 即,两个实体,具有一个辅助密钥。 Here's my structure: 这是我的结构:

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`);

And here's my code in expressjs, using bookshelf: 这是我使用书架的expressjs代码:

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

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

This is a sample code of how I run my query: 这是我如何运行查询的示例代码:

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

However, when I run the application, I get nothing but an empty json: 但是,当我运行应用程序时,除了空的json外,我什么也没有得到:

{}

I've enabled the debug mode in bookshelf, and this is the query it tries to execute: 我已经在书架中启用了调试模式,这是它尝试执行的查询:

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

Now as I've said it, I'm new to bookshelf. 现在,正如我所说的,我是书架的新手。 But this makes no sense; 但是,这没有任何意义。 why doesn't it compare city.city_id to person.city_id (foreign key)? 为什么不将city.city_id与person.city_id(外键)进行比较?

Thank you for your time and answers! 感谢您的时间和答复!

You can get it working by doing the following: 您可以通过执行以下操作使其工作:

1.) Rename the primary keys primary keys to id . 1.)将主键重命名为id The primary keys should be city.id , not city.city_id . 主键应该是city.id ,而不是city.city_id

2.) Change the relation in the User definition to return this.belongsTo(City); 2.)更改用户定义中的关系以return this.belongsTo(City);

3.) You can access the city by doing new User({id: 1}).fetch({ withRelated: ['city'] }); 3.)您可以通过new User({id: 1}).fetch({ withRelated: ['city'] });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM