Skip to content

Commit

Permalink
fix: duplicate insert pivot record if call insertOrUpdate twice
Browse files Browse the repository at this point in the history
  • Loading branch information
kkyouhei committed Feb 11, 2019
1 parent b58d77e commit 40246e4
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/attributes/relations/MorphToMany.ts
Expand Up @@ -173,6 +173,15 @@ export default class MorphToMany extends Relation {
const parentId = record[this.parentKey]
const pivotKey = `${parentId}_${id}_${parent.entity}`

const query = parent.query().newQuery(this.pivot.entity)
.where(this.relatedId, id)
.where(this.id, parentId)
.where(this.type, parent.entity)

if (query.count() > 0) {
return
}

data[this.pivot.entity] = {
...data[this.pivot.entity],

Expand Down
57 changes: 57 additions & 0 deletions test/feature/relations/MorphToMany_Persist.spec.js
Expand Up @@ -207,4 +207,61 @@ describe('Features – Relations – Morph To Many – Persist', () => {
expect(post.tags[0]).toBeInstanceOf(Tag)
expect(post.tags[1]).toBeInstanceOf(Tag)
})

it('can insert or update records', async () => {
class Post extends Model {
static entity = 'posts'

static fields () {
return {
id: this.increment(),
tags: this.morphToMany(Tag, Taggable, 'tag_id', 'taggable_id', 'taggable_type')
}
}
}

class Tag extends Model {
static entity = 'tags'

static fields () {
return {
id: this.increment(),
name: this.string('')
}
}
}

class Taggable extends Model {
static entity = 'taggables'

static fields () {
return {
id: this.increment(),
tag_id: this.number(0),
taggable_id: this.number(0),
taggable_type: this.string('')
}
}
}

createStore([{ model: Post }, { model: Tag }, { model: Taggable }])

const data = {
id: 1,
tags: [
{ id: 1, name: 'news' },
{ id: 2, name: 'cast' }
]
}

await Post.insertOrUpdate({ data: [data] })
await Post.insertOrUpdate({ data: [data] })

const post = Post.query().with('tags').find(1)

expect(post).toBeInstanceOf(Post)
expect(post.tags.length).toBe(2)
expect(post.tags[0]).toBeInstanceOf(Tag)
expect(post.tags[1]).toBeInstanceOf(Tag)
})
})

0 comments on commit 40246e4

Please sign in to comment.