I'm fairly new to bookshelf.js so please bear with me.
Since I'm learning, I'm using MySQL and have a really simple structure. 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:
var City = bookshelf.Model.extend({
tableName: 'city'
});
var User = bookshelf.Model.extend({
tableName: 'people',
city: function(){
return this.hasOne(City);
}
});
This is a sample code of how I run my query:
new User({person_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 the following error
{"code":"ER_BAD_FIELD_ERROR","errno":1054,"sqlState":"42S22","index":0}
I've enabled the debug mode in bookshelf, and this is the query it tries to execute:
{ __cid: '__cid2',
method: 'select',
options: undefined,
bindings: [ undefined, 1 ],
sql: 'select `city`.* from `city` where `city`.`person_id` = ? limit ?' }
Now as I've said it, I'm new to bookshelf. But this makes no sense; why does it select "person_id", instead of "city_id"?
Thank you for your time and answers!
Aucun commentaire:
Enregistrer un commentaire