AdonisJS provided a quick way to track created and updated times, but does not provide shortcuts to track the user who created or last updated the record. Doing so is quite easy.
Modify the migration script to include created_by_id
and updated_by_id
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
// todoschema.js
class TodoSchema extends Schema {
up() {
this.create("todos", (table) => {
table.increments(); // id
table.timestamps(); // created_at and updated_at columns
table
.integer("created_by_id")
.unsigned()
.references("id")
.inTable("users");
table
.integer("updated_by_id")
.unsigned()
.references("id")
.inTable("users");
});
}
down() {
this.drop("todos");
}
}
module.exports = TodoSchema;
|
Both the user id columns are references to the users
table, which is included out of the box in Adonis.
You can now update these values for your create or update operations. You can do this in more than one way - a simple approach using controllers is shown below.
Introduce code in create and update methods in your controller.
1
2
3
4
|
// TodoController.js
const user = await auth.getUser();
todo["created_by_id"] = user.id; // only in create
todo["updated_by_id"] = user.id; // in create and update methods
|