How to use seeds correctly?


Hello folks, I was looking at the documentation on seeds and I saw that in seeds they always use “Database.table(‘table’)” instead of using Lucid using direct to model (Model.create(data)).
Is there any against using the model in the seeds?

1 Like


There is no problem in using Lucid models to seed.
You can see an example on this blog.

1 Like


I understood, but wanted to know some argument to use or not to use. It’s a discussion I’m having with my co-worker, about this.



What you saw in the documentation is seeding using the Query Builder.
Lucid is just some sort of a wrapper for the Query Builder.
There is no sin in using Lucid for seeding.

1 Like


Apart from seeding, there are few situations where the Query Builder can be more useful:

  • If you want to use views (I mean database views, not the views in MVC)
  • If the context makes you think it is better to run raw queries

Otherwise, for seeding, you can use any one of them.

1 Like


Using Lucid will be notably slower for large data sets but both are possible.

1 Like


Interesting to know, could you please justify your statement ? @jacksoncharles

1 Like


@begueradj Mass database inserts are much faster. Using Lucid will save each record individually checking for hooks etc…

1 Like


Mass database inserts are much faster.

You got me. You are right. Thank you for correcting me @jacksoncharles

Lucid bulk insertion:

I checked the source code so that to confirm your statement (createMany()):

for (let index of _.range(numberOfRows)) {
  const row = await this.create(data, index)

This code snippet says clearly that each insertion needs its own trip to the database server.

Query Builder bulk insertion

We can see an example of bulk insertion using Query Builder on the documentation:

const firstUserId = await Database
  .insert([{username: 'foo'}, {username: 'bar'}])

And since Query Builder uses Knex.js under the hood, the last insertion above will be treated by AdonisJs as a single operation. We can justify this by what is written on Knex.js documentation:

Creates an insert query, taking either a hash of properties to be inserted into the row, or an array of inserts, to be executed as a single insert command.


With Lucid, there are clearly more round trips to the database server than when using the Query Builer.

Using Lucid will save each record individually checking for hooks etc…

In fact Query Builder insertions are also affected by the hooks definitions.
For Lucid, insertions are affected by the hooks but not the deletion and update operations (this can be verified on the documentation itself)

Final conclusion

While we can use both Lucid and the Query Builder for seeding, the later one is faster when it comes to bulk insertions. So your colleague and @jacksoncharles are right and I was wrong :slight_smile:

1 Like