使用BookshelfJS/KnexJS的NodeJS脚本中的基本表关联
Basic table association in NodeJS script using BookshelfJS/KnexJS
我的第一个BookshelfJS/KnexJS脚本有一些问题,它有一个表关联。我非常仔细地复制了一对多的例子,只是将其从书籍和页面切换到干燥器和汽车。然而,每当我执行查询并包含withRelated项时,它不会返回相关的数据(在这种情况下是汽车),它只返回驾驶员。
该协会是一个"司机"对许多"汽车"。我甚至在演示中使用了KnexJS脚本来创建表,因此它们与示例表几乎相同。下面是JS脚本:
'use strict';
const Config = require('./config');
const Knex = require( 'knex' )( require('./config').database );
Knex.schema
.createTable('drivers', function(table) {
table.increments('driver_id').primary();
table.string('name');
table.timestamps();
})
.createTable('cars', function(table) {
// using Myisam, since Innodb was throwing an error
table.engine('myisam');
table.increments('car_id').primary();
table.integer('driver_id').references('drivers.driver_id');
table.string('make');
table.string('model');
table.integer('year');
table.timestamps();
})
.then(function(data){
console.log('DONE',data);
})
.catch(function(err){
console.log('ERROR',err);
});
为了获得更多信息,下面是表格结构和表格内容:
mysql> explain drivers;
+------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------+----------------+
| driver_id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| created_at | datetime | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
+------------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
mysql> explain cars;
+------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------+----------------+
| car_id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| driver_id | int(11) | YES | MUL | NULL | |
| make | varchar(255) | YES | | NULL | |
| model | varchar(255) | YES | | NULL | |
| year | int(11) | YES | | NULL | |
| created_at | datetime | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
+------------+------------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)
mysql> select * from drivers;
+-----------+----------+---------------------+------------+
| driver_id | name | created_at | updated_at |
+-----------+----------+---------------------+------------+
| 1 | John Doe | 2015-12-17 00:00:00 | NULL |
| 2 | The Stig | 2015-12-08 00:00:00 | NULL |
+-----------+----------+---------------------+------------+
2 rows in set (0.00 sec)
mysql> select * from cars;
+--------+-----------+-----------+--------+------+---------------------+------------+
| car_id | driver_id | make | model | year | created_at | updated_at |
+--------+-----------+-----------+--------+------+---------------------+------------+
| 1 | 1 | Chevrolet | Camaro | 2014 | 2015-12-18 00:00:00 | NULL |
| 2 | 1 | Acura | RSX-S | 2004 | 2015-12-11 00:00:00 | NULL |
| 3 | 2 | Ford | Focus | 2004 | 2015-12-18 00:00:00 | NULL |
| 4 | 2 | Nissan | Maxima | 2001 | 2015-12-17 00:00:00 | NULL |
| 5 | 2 | Geo | Metro | 1998 | 2015-12-18 00:00:00 | NULL |
+--------+-----------+-----------+--------+------+---------------------+------------+
5 rows in set (0.00 sec)
然后是带有模型和查询执行的实际NodeJS脚本:
// app.js
'use strict';
const Config = require('./config');
const Bookshelf = require('./bookshelf');
var Driver = Bookshelf.Model.extend({
tableName: 'drivers',
cars: function() {
return this.hasMany(Car);
}
});
var Car = Bookshelf.Model.extend({
tableName: 'cars',
driver: function() {
return this.belongsTo( Driver );
}
});
new Driver()
.where({
driver_id: 2
})
.fetch({
withRelated: ['cars']
})
.then(function(driver) {
console.log('RELATED CAR:', JSON.stringify(driver));
console.log('DRIVER DATA', driver);
});
此外,这里还有bookshelf.js文件,其中包含KnexJS和BookshelfJS连接:
// bookshelf.js
'use strict';
var knex = require( 'knex' )( require('./config').database );
module.exports = require('bookshelf')( knex );
以下是执行app.js 时的控制台输出
RELATED CAR: {"driver_id":2,"name":"The Stig","created_at":"2015-12-08T07:00:00.000Z","updated_at":null,"cars":[]}
DRIVER DATA ModelBase {
attributes:
{ driver_id: 2,
name: 'The Stig',
created_at: Tue Dec 08 2015 00:00:00 GMT-0700 (MST),
updated_at: null },
_previousAttributes:
{ driver_id: 2,
name: 'The Stig',
created_at: Tue Dec 08 2015 00:00:00 GMT-0700 (MST),
updated_at: null },
changed: {},
relations:
{ cars:
CollectionBase {
model: [Object],
length: 0,
models: [],
_byId: {},
relatedData: [Object] } },
cid: 'c1',
_knex: null }
我不确定问题是什么,我有一种感觉,我忽略了一些相当简单的事情。
谢谢!
出现两个问题
cars.driver_id
需要无符号,就像它在驱动程序表中引用的ID列一样- 我将表索引列创建为
${singular_table_name}_id
,根据我的经验,这是最常见的方法,但BookshelfJS希望它只是id
。因此,我可以将ID列名更改为仅id
,也可以将idAttribute
值设置为${singular_table_name}_id
经过上述更改后,一切正常。
相关文章:
- nodejs-expressjs上传图像并显示它们
- TypeError:在不兼容的接收器nodejs上调用了方法Uint8Array.length
- NodeJS-readline暂停和恢复事件发射器(逐行读取)
- NodeJS日期格式不起作用
- Nested Q.all nodejs
- Nodejs API控制器,用于在API之间切换
- 否'访问控制允许来源'标头存在于IISNOde中请求的资源(AngularJS+NodeJs)上
- 如何在大型nodeJS代码的基础上逐步引入typescript
- 在Nodejs中Express输入DEBUG=app时权限被拒绝/bin
- 无法使用nodeJS在html中设置Image src
- 与域在同一台计算机上运行的NODEJS服务器的CORS错误
- NodeJS API调用中Array中的Push和Pull元素
- 基于api密钥的NodeJS web服务
- 在gump和nodejs中使用Typescript时,未定义对require和exports的引用
- “util.inherits”和在NodeJS中扩展原型之间的区别
- 将一个方法转换为promise:Nodejs
- 多维关联数组的最后一个索引
- nodejs中匿名函数的使用
- 在 NodeJS 中,有没有一种类似于 dependant 的方法:Ruby 中的 :d estroy 用于关联记录
- 使用BookshelfJS/KnexJS的NodeJS脚本中的基本表关联