How to access other models from a setter

I need to be able to access a second model from the first models setters, but because that means making the model async, Adonis does not like it. Any ideas how I can go about this.

Here is what I was trying to do.

async setHeaderText(text) {
    var settings = await Setting.find(1)
    return `${settings.invoice_header_text}


but it gives me the error

insert into `invoices` (`created_at`, `description`, `footerText`, `headerText`, `invoiceDate`, `updated_at`, `user_id`) values ('2019-05-17 20:37:37', 'Flying hours', {}, {}, '2019-05-17 20:37:37', '2019-05-17 20:37:37', 1) - ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , '2019-05-17 20:37:37', '2019-05-17 20:37:37', 1)' at line 1

Any ideas?

1 Like

I think it is better to avoid calling a controller from an other one, or a model from an other one. And actually you stated this through your question when you said AdonisJs does not like this.

Setters are called when assigning a value to a model instance.

So my suggestion is to change your approach on how this should be tackled.
Unfortunately I did not face a similar situation, so I can not provide a useful alternative. Hope someone else will do.

I solved it with Database hooks


class Invoice extends Model {

static boot() {
    this.addHook('afterCreate', async (invoiceInstance) => {
      var settings = await Setting.find(1)
      invoiceInstance.headerText = `${settings.invoice_header_text}
      invoiceInstance.footerText = `${settings.invoice_footer_text}
1 Like