|
| 1 | +import { createStore } from 'test/support/Helpers' |
| 2 | +import { Model } from '@vuex-orm/core' |
| 3 | + |
| 4 | +describe('Feature - Relations - Belongs To Many', () => { |
| 5 | + class User extends Model { |
| 6 | + static entity = 'users' |
| 7 | + |
| 8 | + static fields() { |
| 9 | + return { |
| 10 | + id: this.attr(null), |
| 11 | + roles: this.belongsToMany(Role, RoleUser, 'user_id', 'role_id') |
| 12 | + } |
| 13 | + } |
| 14 | + |
| 15 | + roles!: Role[] |
| 16 | + } |
| 17 | + |
| 18 | + class Role extends Model { |
| 19 | + static entity = 'roles' |
| 20 | + |
| 21 | + static fields() { |
| 22 | + return { |
| 23 | + id: this.attr(null) |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + class RoleUser extends Model { |
| 29 | + static entity = 'roleUser' |
| 30 | + |
| 31 | + static primaryKey = ['role_id', 'user_id'] |
| 32 | + |
| 33 | + static fields() { |
| 34 | + return { |
| 35 | + role_id: this.attr(null), |
| 36 | + user_id: this.attr(null) |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + beforeEach(async () => { |
| 42 | + createStore([User, Role, RoleUser]) |
| 43 | + |
| 44 | + await User.create({ |
| 45 | + data: [ |
| 46 | + { id: 1, roles: [{ id: 3 }, { id: 4 }] }, |
| 47 | + { id: 2, roles: [{ id: 3 }] } |
| 48 | + ] |
| 49 | + }) |
| 50 | + }) |
| 51 | + |
| 52 | + it('can resolve queries without deleted relation (default)', async () => { |
| 53 | + await Role.softDelete(3) |
| 54 | + |
| 55 | + const users = User.query() |
| 56 | + .with('roles') |
| 57 | + .findIn([1, 2]) as User[] |
| 58 | + |
| 59 | + expect(users[0].roles.length).toBe(1) |
| 60 | + expect(users[0].roles[0].$trashed()).toBe(false) |
| 61 | + |
| 62 | + expect(users[1].roles.length).toBe(0) |
| 63 | + }) |
| 64 | + |
| 65 | + it('can include deleted relations using `withTrashed` clause', async () => { |
| 66 | + await Role.softDelete(3) |
| 67 | + |
| 68 | + const users = User.query() |
| 69 | + .withTrashed() |
| 70 | + .with('roles') |
| 71 | + .findIn([1, 2]) as User[] |
| 72 | + |
| 73 | + expect(users[0].roles.length).toBe(2) |
| 74 | + expect(users[0].roles[0].$trashed()).toBe(true) |
| 75 | + expect(users[0].roles[1].$trashed()).toBe(false) |
| 76 | + |
| 77 | + expect(users[1].roles.length).toBe(1) |
| 78 | + expect(users[1].roles[0].$trashed()).toBe(true) |
| 79 | + }) |
| 80 | + |
| 81 | + it('can resolve only deleted relations using `onlyTrashed` clause', async () => { |
| 82 | + await Role.softDelete(3) |
| 83 | + |
| 84 | + const users = User.query() |
| 85 | + .onlyTrashed() |
| 86 | + .with('roles') |
| 87 | + .findIn([1, 2]) as User[] |
| 88 | + |
| 89 | + expect(users[0].roles.length).toBe(1) |
| 90 | + expect(users[0].roles[0].$trashed()).toBe(true) |
| 91 | + |
| 92 | + expect(users[1].roles.length).toBe(1) |
| 93 | + expect(users[1].roles[0].$trashed()).toBe(true) |
| 94 | + }) |
| 95 | +}) |
0 commit comments