|
1
|
|
|
import Relation from "../Relation.js"; |
|
2
|
|
|
import {ModelStaticInterface} from "../../../JeloquentInterfaces"; |
|
3
|
|
|
import Collection from "../../Collection"; |
|
4
|
|
|
import ForeignKey from "../Field/ForeignKey"; |
|
5
|
|
|
|
|
6
|
|
|
/** |
|
7
|
|
|
* |
|
8
|
|
|
*/ |
|
9
|
|
|
export default class HasMany extends Relation { |
|
10
|
|
|
|
|
11
|
|
|
localKey: string; |
|
12
|
|
|
|
|
13
|
|
|
constructor(model: ModelStaticInterface, foreignKey: string, localKey: string) { |
|
14
|
|
|
super(model, foreignKey); |
|
15
|
|
|
this.localKey = localKey ?? 'id'; |
|
16
|
|
|
} |
|
17
|
|
|
|
|
18
|
|
|
get count(): number { |
|
19
|
|
|
const indexes = globalThis.Store.database().indexes(this.model.className); |
|
20
|
|
|
return indexes.get(this.foreignKey).get(this.$parent.primaryKey)?.size ?? 0; |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
get originalValue(): unknown { |
|
24
|
|
|
return this.getValueByParentKey('originalPrimaryKey'); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
get value(): unknown { |
|
28
|
|
|
return this.getValueByParentKey('primaryKey'); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
getRelationalFields():Array<ForeignKey> { |
|
32
|
|
|
return []; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
setName(): HasMany { |
|
36
|
|
|
const parentClassName = this.$parent.snakeCaseClassName; |
|
37
|
|
|
const modelClassName = this.model.snakeCaseClassName; |
|
38
|
|
|
|
|
39
|
|
|
this.foreignKey = `${parentClassName}_id`; |
|
40
|
|
|
this.$name = `${modelClassName}s`; |
|
41
|
|
|
return this; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
protected getValueByParentKey(parentProperty): Collection { |
|
45
|
|
|
const keyIndex = this.model.getIndexByKey(this.foreignKey); |
|
46
|
|
|
return globalThis.Store.database().find(this.model.className, |
|
47
|
|
|
[...keyIndex.get(this.$parent[parentProperty])?.values() ?? []] |
|
48
|
|
|
); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
protected setParentProperties(): HasMany { |
|
52
|
|
|
super.setParentProperties(); |
|
53
|
|
|
|
|
54
|
|
|
Object.defineProperty(this.$parent, |
|
55
|
|
|
`${this.name}Count`, { |
|
56
|
|
|
get: () => { |
|
57
|
|
|
return this.count; |
|
58
|
|
|
}, |
|
59
|
|
|
} |
|
60
|
|
|
); |
|
61
|
|
|
|
|
62
|
|
|
Object.defineProperty(this.$parent, |
|
63
|
|
|
`has${this.model.className}s`, { |
|
64
|
|
|
get: () => { |
|
65
|
|
|
return this.count > 0; |
|
66
|
|
|
}, |
|
67
|
|
|
} |
|
68
|
|
|
); |
|
69
|
|
|
return this; |
|
70
|
|
|
} |
|
71
|
|
|
} |