adonisjs / lucid

AdonisJS SQL ORM. Supports PostgreSQL, MySQL, MSSQL, Redshift, SQLite and many more
https://lucid.adonisjs.com/
MIT License
1.08k stars 195 forks source link

How to operate a database in custom commands #1055

Closed namesfang closed 1 month ago

namesfang commented 1 month ago

Package version

21.2.0

Describe the bug

I customize a command admin:create that prompts at run node ace admin:create TypeError: Cannot read properties of undefined (reading 'query')

I'm not sure if it's a bug? How to solve this problem.

@adonisjs/core 6.12.1 better-sqlite3 11.3.0 mysql2 3.11.3


import { BaseCommand } from '@adonisjs/core/ace'
import type { CommandOptions } from '@adonisjs/core/types/ace'
import Configuration from '#models/configuration'

export default class Create extends BaseCommand {
  static commandName = 'admin:create'
  static description = ''

  static options: CommandOptions = {}

  async run() {
    const d = await Configuration.find(1)
    console.log('?d', d) // TypeError: Cannot read properties of undefined (reading 'query')
  }
}

### Reproduction repo

_No response_
RomainLanz commented 1 month ago

Hey @namesfang! 👋🏻

You are missing the startApp property in your command option.

export default class GreetCommand extends BaseCommand {
  static options = {
    startApp: true
  }

  async run() {
    console.log(this.app.isStarted) // true
  }
}

📚 https://docs.adonisjs.com/guides/ace/creating-commands#command-metadata

namesfang commented 1 month ago

Hey @namesfang! 👋🏻

You are missing the startApp property in your command option.

export default class GreetCommand extends BaseCommand {
  static options = {
    startApp: true
  }

  async run() {
    console.log(this.app.isStarted) // true
  }
}

📚 https://docs.adonisjs.com/guides/ace/creating-commands#command-metadata

Thanks, Your answer solved my problem.