我有两个模型“比赛”和“团队”。它们的架构如下:-
migrations/20180809010359_teams.js
exports.up = function(knex, Promise) {
return knex.schema.createTable('teams', (table) => {
table.increments('id');
table.string('name').notNullable();
table.text('image').notNullable().defaultTo('');
table
.enu(
'sport',
['cricket', 'football'],
{ useNative: true, enumName: 'team_sport' }
)
.notNullable();
table.unique(['name', 'sport']);
table.timestamps();
});
};
exports.down = function(knex, Promise) {
return knex.schema.dropTable('teams');
};
migrations/20180809043147_matches.js
exports.up = function(knex, Promise) {
return knex.schema.createTable('matches', (table) => {
table.increments('id');
table.string('title').notNullable();
table.integer('team1').notNullable();
table.integer('team2').notNullable();
table.text('description').notNullable();
table.dateTime('dateTime').notNullable();
table.string('pollUrl').nullable();
table.text('codes').nullable();
table.json('images').nullable();
table
.enu(
'sport',
['cricket', 'football'],
{ useNative: true, enumName: 'match_sport' }
)
.notNullable();
table.foreign('team1').references('teams.id');
table.foreign('team2').references('teams.id');
table.unique(['team1', 'team2', 'dateTime']);
table.timestamps();
}).raw(`
alter table "matches"
add constraint "ensure_both_teams_are_diff" check(
team1 <> team2
)
`);
};
exports.down = function(knex, Promise) {
return knex.schema.dropTable('matches');
};
可以从迁移中推论得出。我试图指定一个Match属于一个Team作为team1列,而另一个Team属于team2列。
这是我的Team
和Match
的模型:-
models/Match.js
const bookshelf = require('../bookshelf');
const Match = bookshelf.Model.extend({
tableName: 'matches',
hasTimestamps: true,
team1: function() {
return this.belongsTo('Team', 'team1');
},
team2: function() {
return this.belongsTo('Team', 'team2');
}
});
module.exports = bookshelf.model('Match', Match);
models/Team.js
const bookshelf = require('../bookshelf');
const { Match } = require('./index');
const Team = bookshelf.Model.extend({
tableName: 'teams',
hasTimestamps: true,
matches: function() {
return this.hasMany('Match', 'team1');
}
});
module.exports = bookshelf.model('Team', Team);
所以,我要坚持的重点是如何获得该团队可能在team1或team2列中的所有比赛
我确实尝试将matches
函数修改为:-
matches: function() {
return this.hasMany('Match', 'team1').add(this.hasMany('Match', 'team2').toJSON());
}
但是错误到(node:47098) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'parentFk' of undefined
。