Extending model

hello. can i extend existing model and add extra field to him? I have User model in my app, me need make admin model, but admin is user, he has the same fields + extra filed. how it will looks like in database, what migrations do i need?

class User extends Model {
}
class Admin extends User {
}

Sorry for my english :slight_smile:

1 Like

You can extend your Admin model class the same way User extends Model class. But I recommend you to use traits and move all common methods and relationships in it.

https://adonisjs.com/docs/4.1/traits

Also if you want User and Admin model use the same table in the database there is a static method for it:

class Admin extends Model {
  static get table () {
    return 'users'
  }
}

So Lucid will use users table for admin model instead of searching for non-existing admins table.

2 Likes

I think that traits only for extending methods, but what about fields? example admin will has field “reputation”. It’s not needed for standart user.

do you speak russian?

Traits can have anything you want. Not only methods.

In a user model you can exclude reputation field like this:

class User extends Model {
  static get hidden () {
    return ['reputation']
  }
}

See: https://adonisjs.com/docs/4.1/lucid#_hiding_fields

P.S. Да, я говорю по-русски, но на форуме лучше все же использовать англ :slight_smile:

2 Likes

then what about database table? it will be contain all fields of all entities. is it right?

Yep, why not?

1 Like

Understand! thanks you. But in my case i decide make profiles tables for each user type.