Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/pinia-orm/src/schema/Schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,8 @@ export class Schema {
// If the `key` is not `null`, that means this record is a nested
// relationship of the parent model. In this case, we'll attach any
// missing foreign keys to the record first.
if (key !== null) { (parent.$fields()[key] as Relation).attach(parentRecord, record) }
console.log('schema', parent.$fields(), key, model.$entity(), parent.$entity())
if (key !== null) { (parent.$fields()[key] as Relation)?.attach(parentRecord, record) }

// Next, we'll generate any missing primary key fields defined as
// uid field.
Expand Down
103 changes: 103 additions & 0 deletions packages/pinia-orm/tests/feature/relations/morph_many_save.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,107 @@ describe('feature/relations/morph_many_save', () => {
}
})
})

it('can save complicated polymorphs', () => {
Model.clearRegistries()
class Comment extends Model {
static entity = 'comments'
static fields () {
return {
id: this.number(0),
url: this.string(''),
content_id: this.number(0),
content_type: this.string(''),
content: this.morphTo([Video, Post], 'content_id', 'content_type'),
creator_id: this.string(null),
creator: this.belongsTo(Person, 'creator_id')
}
}
}

class Person extends Model {
static entity = 'person'
static primaryKey = 'id'

static fields () {
return {
id: this.uid(),
job: this.attr(''),
comments: this.hasMany(Comment, 'creator_id')
}
}
}

class Video extends Model {
static entity = 'videos'
static fields () {
return {
id: this.number(0),
link: this.string(''),
comments: this.morphMany(Comment, 'content_id', 'content_type')
}
}
}
class Post extends Model {
static entity = 'posts'
static fields () {
return {
id: this.number(0),
title: this.string(''),
comments: this.morphMany(Comment, 'content_id', 'content_type')
}
}
}
const person = useRepo(Person)

person.save({
id: 'p',
job: 'dev',
comments: [
{
id: 1,
content_id: 4,
content_type: 'posts',
content: { id: 4, title: 'a post' },
creator_id: 'p'
},
{
id: 2,
content_id: 3,
content_type: 'videos',
content: { id: 3, link: 'test' },
creator_id: 'p'
}
]
})

assertState({
posts: {
4: { id: 4, title: 'a post' }
},
videos: {
3: { id: 3, link: 'test' }
},
comments: {
1: {
id: 1,
url: '',
creator_id: 'p',
content_id: 4,
content_type: 'posts'
},
2: {
id: 2,
url: '',
creator_id: 'p',
content_id: 3,
content_type: 'videos'
}
},
person: {
p: { id: 'p', job: 'dev' }
}

})
})
})