我有两个表:devices
和 diagnostics
。
在注册设备
之前运行诊断
。会有一个 cpu_id
作为诊断
运行的一部分保存。那么设备
一旦注册,也会有一个cpu_id
记录在其上。
这是多对一的关系,这里的外键是chip_id
。
我对两个表尝试了以下操作,但一无所获:
设备
diagnostics: function () {
var Diagnostic = require('./db').model('Diagnostic');
return this.hasMany(Diagnostic, 'chip_id');
}
诊断
device: function () {
var Device = require('./config/db').model('Device');
return this.belongsTo(Device, 'chip_id');
}
我做错了什么?
最佳答案
您需要在模型中定义 hasMany 和 BelongsTo,然后您需要像这样检索您的关系
Book.where({id: 1}).fetch({withRelated: ['author']}).then(function(book) {
console.log(JSON.stringify(book.related('author')));
});
使用 withRelated 标记您需要该关系以及执行预先加载的相关函数
关于javascript - 书架JS : How to define relationship with a foreign key other than ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31841496/