How can I create an update_by field on a model

Hi! first of all sorry for my bad English.

Well i’m learning to use Adonis and al goes fine so far. I can add the user_id on a model to link the model with the user that created the register, but i want to add an update by model too. Sincerely i don’t know how can i achieve this.

This is my poroject Schema

class ProjectSchema extends Schema {
  up () {
    this.create('projects', (table) => {
      table.string('title', 255)

This is the controller

async create({ auth, request }) {
    const user = await auth.getUser();
    const { title } = request.all();
    const project = new Project();
    await user.projects().save(project);
    return project;

And the models for projects and users

class Project extends Model {
  user() {
    return this.belongsTo('App/Models/User');

------------------------------------ User model
class User extends Model {
  static boot () {

     * A hook to hash the user password before saving
     * it to the database.
     * Look at `app/Models/Hooks/User.js` file to
     * check the hashPassword method
    this.addHook('beforeCreate', 'User.hashPassword')

   * A relationship on tokens is required for auth to
   * work. Since features like `refreshTokens` or
   * `rememberToken` will be saved inside the
   * tokens table.
   * @method tokens
   * @return {Object}
  tokens () {
    return this.hasMany('App/Models/Token')

  projects () {
    return this.hasMany('App/Models/Project')

Well like I say before I like to add in the project an updated_by, to make it change every time that a user modifies one project, to have a record of the user that create the project, and the last user that modifies the record but i can’t find the way to do this, is the first time that i use javascript for backend i always use Django (python) then sorry for my noob question

1 Like

Hi @marcosguerrini

Do you want to keep update history or you want to keep only last updated_by?

If only last, then you can add


And then in controller add updated_by:

Or you can create new beforeUpdate / beforeSave hook inside user model that adds updated_by, so you don’t have to deal with it in controller


Thanks very much. I only want to keep the last updated_by only.

Last question about it, i don’t need to add hasMany, and hasOne in the model for that relationship?


Depends if and how you want to query it.
If you want to do something like

// Get users with projects they have updated

Then you should add

// User.js
updates () {
  return this.hasMany('App/Models/Projects')

And opposite, if you want to do Project.query().with(‘updater’).fetch()

But if you query only one way or do not query at all, then there is no need to add relationships to models.

(With one way you still need to add relationship into one model)


Excellent, believe it or not, in 2 answers you have left me much clearer things that more than 5 tutorials have not done!


1 Like