0
我似乎遇到了從相關模型中檢索屬性的問題。書架獲取相關數據屬性爲空
型號:
// DB = export of Bookshelf
// Signup model
var DB = require('../db').DB;
var UserMeta = require('./usersmeta');
var Signup = DB.Model.extend({
tableName: 'tblSignups',
idAttribute: 'id',
hasTimestamps: true,
usermeta: function() {
return this.belongsTo(UserMeta);
}
});
module.exports = Signup;
// Usermeta model
var DB = require('../db').DB;
var User = require('./users');
var UserMeta = DB.Model.extend({
tableName: 'tblUsersMeta',
idAttribute: 'id',
hasTimestamps: true,
user: function() {
return this.belongsTo(User);
}
});
module.exports = UserMeta;
管理員註冊路線:
router.get('/signups', function(req, res, next) {
model.SignUp.fetchAll({withRelated: ['usermeta']}).then(function(collection) {
for(var i = 0; i < collection.toArray().length; i++){
console.log('Signup ' + i + '\n--------------------------');
console.log(collection.toArray()[i]);
console.log('Related usermeta\n--------------------------');
console.log(collection.toArray()[i].related('usermeta'));
}
res.render('admin/pages/signups', {title: 'signups', error: false, signups: collection.toArray()});
}).catch(function(err) {
res.status(500).json({error: true, data: {message: err.message}});
});
});
這是控制檯日誌顯示我:
Signup 0
--------------------------
ModelBase {
attributes:
{ id: 2,
usermeta_id: 5,
state: 'pending',
created_at: Thu May 05 2016 17:21:13 GMT+0200 (Romance Daylight Time),
updated_at: Thu May 05 2016 17:21:13 GMT+0200 (Romance Daylight Time) },
_previousAttributes:
{ id: 2,
usermeta_id: 5,
state: 'pending',
created_at: Thu May 05 2016 17:21:13 GMT+0200 (Romance Daylight Time),
updated_at: Thu May 05 2016 17:21:13 GMT+0200 (Romance Daylight Time) },
changed: {},
relations:
{ usermeta:
ModelBase {
attributes: {},
_previousAttributes: {},
changed: {},
relations: {},
cid: 'c38',
relatedData: [Object] } },
cid: 'c35',
id: 2 }
Related usermeta
--------------------------
ModelBase {
attributes: {},
_previousAttributes: {},
changed: {},
relations: {},
cid: 'c38',
relatedData:
RelationBase {
targetTableName: 'tblUsersMeta',
targetIdAttribute: 'id',
type: 'belongsTo',
target:
{ [Function]
NotFoundError: [Function: ErrorCtor],
NoRowsUpdatedError: [Function: ErrorCtor],
NoRowsDeletedError: [Function: ErrorCtor] },
foreignKey: 'tblUsersMetum_id',
parentId: undefined,
parentTableName: 'tblSignups',
parentIdAttribute: 'id',
parentFk: undefined } }
因此,您可以看到相關模型屬性爲空。我保存了我的usermeta,如下所示:
userMeta.save().then(function(usermeta) {
var signup = new model.SignUp({
usermeta_id: usermeta.attributes.id
});
signup.save().then(function() {
req.flash('success', 'Success!');
res.redirect('/signup');
}).catch(function(err) {
res.status(500).json({error: true, data: {message: err.message}});
});
}).catch(function (err) {
res.status(500).json({error: true, data: {message: err.message}});
});
在數據庫中,usermeta的id(在註冊表中)設置正確。我在這裏做錯了什麼?
這是一對一的關係,但確實它應該是「hasOne」。謝謝! – Goowik