diff --git a/framework/core/js/src/common/Model.ts b/framework/core/js/src/common/Model.ts index 9cea14335..1bc29431e 100644 --- a/framework/core/js/src/common/Model.ts +++ b/framework/core/js/src/common/Model.ts @@ -110,6 +110,7 @@ export default abstract class Model { } if ('attributes' in data) { + this.data.attributes ||= {}; Object.assign(this.data.attributes, data.attributes); } @@ -295,16 +296,14 @@ export default abstract class Model { static hasOne(name: string): () => M | null | false; static hasOne(name: string): () => M | false { return function (this: Model) { - if (this.data.relationships) { - const relationshipData = this.data.relationships[name]?.data; + const relationshipData = this.data.relationships?.[name]?.data; - if (relationshipData instanceof Array) { - throw new Error(`Relationship ${name} on model ${this.data.type} is plural, so the hasOne method cannot be used to access it.`); - } + if (relationshipData && relationshipData instanceof Array) { + throw new Error(`Relationship ${name} on model ${this.data.type} is plural, so the hasOne method cannot be used to access it.`); + } - if (relationshipData) { - return this.store.getById(relationshipData.type, relationshipData.id) as M; - } + if (relationshipData) { + return this.store.getById(relationshipData.type, relationshipData.id) as M; } return false; @@ -321,16 +320,14 @@ export default abstract class Model { */ static hasMany(name: string): () => (M | undefined)[] | false { return function (this: Model) { - if (this.data.relationships) { - const relationshipData = this.data.relationships[name]?.data; + const relationshipData = this.data.relationships?.[name]?.data; - if (!(relationshipData instanceof Array)) { - throw new Error(`Relationship ${name} on model ${this.data.type} is singular, so the hasMany method cannot be used to access it.`); - } + if (relationshipData && !(relationshipData instanceof Array)) { + throw new Error(`Relationship ${name} on model ${this.data.type} is singular, so the hasMany method cannot be used to access it.`); + } - if (relationshipData) { - return relationshipData.map((data) => this.store.getById(data.type, data.id)); - } + if (relationshipData) { + return relationshipData.map((data) => this.store.getById(data.type, data.id)); } return false;