0
3 개 테이블 함께 관련하는 방법 나는 다음과 같은 테이블이있어
있는 해당 모델에 말했다 테이블 :
- 여기
users
books
book_reviews
const BookReview = require('./BookReview').model;
const User = require('./User').model;
module.exports.model = bookshelf.Model.extend({
tableName: 'books',
user: function() {
return this.hasOne(User, 'user_id');
},
reviews: function() {
return this.hasMany(BookReview);
}
});
module.exports.model = bookshelf.Model.extend({
tableName: 'book_reviews',
user: function() {
this.hasMany(User, 'user_id');
}
});
module.exports.model = bookshelf.Model.extend({
tableName: 'users',
reviews: function() {
return this.belongsToMany(BookReview, 'user_id');
}
});
나는 책을보고는 현재 다음 문으로하고있다가이 모든 리뷰를 가져 오기 위해 노력하고있어 :
return Book.forge({
id: req.params.id,
type: req.params.type
}).fetch({withRelated: ['reviews'], require: true}).then(function(book) {
console.log(book.toJSON());
return book;
}).catch(function(err) {
throw new Error(err.message);
});
을};
그리고 위에서 book.toJSON()
의 출력은 다음과 같습니다 위에서) book.toJSON (에서
출력 :
{ id: 1,
type: 'novel',
slug: 'catcher-in-the-rye',
user_id: 1,
name: 'Catcher in the Rye',
created_at: Tue Oct 04 2016 22:35:42 GMT-0700 (PDT),
updated_at: Tue Oct 04 2016 22:35:42 GMT-0700 (PDT),
reviews:
[ { id: 14,
user_id: 2,
book_id: 1,
rating: 3,
review: 'Test',
created_at: Wed Oct 05 2016 20:47:34 GMT-0700 (PDT),
updated_at: Wed Oct 05 2016 20:47:34 GMT-0700 (PDT) } ] }
하지만 내 의도가 reviews
의 각각에 대한 참조를 가질 것입니다 users
테이블, 그들은 현재하지 않습니다. 어떻게 그들을 함께 연결할 수 있습니까?
다음과 같이 나타납니다 :'처리되지 않은 거부 오류 : book_reviews hasMany 관계에 유효한 대상 모델이 정의되어야 함' –
BookReview 모델'user' 관계에서 사용자 ID가 아닌 검토 ID를 넣어야한다고 생각합니다. 예 'this.hasMany (User, 'review_id')'. 그 외에는 내가 잘못 본 것이 없습니다. – blah238
그래, 실제로 순환 종속성이 발생했다. 나는 그것을 다음과 같이 변경했다 :'module.exports.model = bookshelf.Model.extend ({ tableName : 'book_reviews', user : function {) { const user = require ('./ User'). model ; this.belongsTo (User, 'user_id'); }'감사합니다. 감사합니다! –