-
Notifications
You must be signed in to change notification settings - Fork 643
Closed
Labels
Description
Following this example , I am not getting the beforeInsert method to work in the mappings (see my Notes class below). I fully recognize this is likely "user's error", but at the risk of being seared; can someone confirm if I've set this up incorrectly?
an alter to the table to support polymorphic inserts
exports.up = function (knex) {
return knex.schema.table('notes', function (table) {
table.string('noteable_type')
table.integer('noteable_id')
})
}
exports.down = function (knex) {
return knex.schema.table('notes', function (t) {
t.dropColumn('noteable_type')
t.dropColumn('noteable_id')
})
}
my polymorphic note
import { Model } from 'objection';
import ITimestamped from './timestamped';
export interface INote {
id?:number;
note: string;
author_id: number;
noteable_id?: number;
noteable_type?: string;
}
class Note extends Model implements INote,ITimestamped{
created_at: string;
updated_at: string;
id?: number;
note: string;
author_id: number;
noteable_id: number;
noteable_type: string;
static ObjectType:string = "notes";
static get tableName() {
return this.ObjectType;
}
}
export default Note;
an object that will have notes
import { Model } from "objection";
import Note from "./note";
import ITimestamped from "./timestamped";
import Knex = require("knex");
export interface IBike {
id?:number;
serial_number: string;
model?: string;
}
class Bike extends Model implements IBike,ITimestamped {
serial_number: string;
model?: string;
id?: number;
created_at: string;
updated_at: string;
static ObjectType:string = "bikes";
static get tableName() {
return this.ObjectType;
}
static get relationMappings() {
return {
notes: {
relation: Model.HasManyRelation,
modelClass: Note,
filter(builder:Knex) {
builder.where('noteable_type', 'Bike');
},
beforeInsert(model:Note) { // <<----this guy, not working for me
model.noteable_type = 'Bike';
},
join: {
from:`${Bike.ObjectType}.id`,
to: `${Note.ObjectType}.noteable_id`,
}
},
};
}
}
export default Bike;
a test (which fails at the end)
test(`Can create a note`, async () => {
const temp: Bike = await Bike.query().first();
expect(temp).not.toBeNull();
const notes = await temp.$relatedQuery("notes");
const notesLength = notes.length;
const rawNote = { note: "hello", author_id: 1 };
// create the note
await temp
.$relatedQuery("notes")
.insertGraph(rawNote)
const newLength = await temp.$relatedQuery("notes");
console.log(newLength,'newlength');
expect(newLength.length).toBeGreaterThan(notesLength);
});
