11import { Store } from 'vuex'
22import { isNullish , isArray , assert } from '../support/Utils'
33import { Element , Item , Collection } from '../data/Data'
4+ import { Query } from '../query/Query'
45import { NonEnumerable } from './decorators/NonEnumerable'
56import { Attribute } from './attributes/Attribute'
67import { Attr } from './attributes/types/Attr'
@@ -253,12 +254,10 @@ export class Model {
253254 }
254255
255256 /**
256- * Set the store instance .
257+ * Get the model fields for this model .
257258 */
258- $setStore ( store : Store < any > ) : this {
259- this . _store = store
260-
261- return this
259+ get $fields ( ) : ModelFields {
260+ return this . $self . schemas [ this . $entity ]
262261 }
263262
264263 /**
@@ -275,10 +274,19 @@ export class Model {
275274 }
276275
277276 /**
278- * Get the model fields for this model .
277+ * Create a new query instance .
279278 */
280- get $fields ( ) : ModelFields {
281- return this . $self . schemas [ this . $entity ]
279+ $query ( ) : Query < this> {
280+ return new Query ( this . $store , this )
281+ }
282+
283+ /**
284+ * Set the store instance.
285+ */
286+ $setStore ( store : Store < any > ) : this {
287+ this . _store = store
288+
289+ return this
282290 }
283291
284292 /**
@@ -450,6 +458,37 @@ export class Model {
450458 return this . $toJson ( this , { relations : false } )
451459 }
452460
461+ /**
462+ * Delete the model from the database.
463+ */
464+ async $delete ( ) : Promise < boolean > {
465+ const key = this . $getKeyName ( )
466+
467+ return isArray ( key )
468+ ? this . $deleteByCompositeKeyName ( key )
469+ : this . $deleteByKeyName ( key )
470+ }
471+
472+ /**
473+ * Delete the model from the database by ID.
474+ */
475+ protected async $deleteByKeyName ( key : string ) : Promise < boolean > {
476+ return ! ! ( await this . $query ( ) . destroy ( this [ key ] ) )
477+ }
478+
479+ /**
480+ * Delete the model from the database by composite key.
481+ */
482+ protected async $deleteByCompositeKeyName ( keys : string [ ] ) : Promise < boolean > {
483+ const query = this . $query ( )
484+
485+ keys . forEach ( ( key ) => {
486+ query . where ( key , this [ key ] )
487+ } )
488+
489+ return ( await query . delete ( ) ) . length > 0
490+ }
491+
453492 /**
454493 * Serialize this model, or the given model, as POJO.
455494 */
0 commit comments