Ready to get started?
Join Adocasts Plus for $8/mo, or sign into an existing Adocasts Plus account, to get access to all of our lessons.
Building with AdonisJS & Inertia #4.2
Defining Our Lucid Models & Relationships
We'll convert our migrations into Lucid Models and define both sides of the relationships so they're ready to go.
- Created by
- @tomgobich
- Published
Join the Discussion 7 comments
-
If we want to define single or multi column indexes for our tables, do we do that in the migrations files?
1-
Responding to aaron-ford
Yeah, you can do that via a migration! There is an
indexanddropIndexmethod for that. The KnexJS documentation has more info on the options these accept, which will vary depending on your database driver.import { BaseSchema } from '@adonisjs/lucid/schema' export default class extends BaseSchema { protected tableName = 'index_examples' async up() { this.schema.alterTable(this.tableName, (table) => { // single table.index('column_one') // multi-column table.index(['column_two', 'column_three']) // custom named table.index(['column_four'], 'custom_index_name', { /* additional opts */ }) }) } async down() { this.schema.alterTable(this.tableName, (table) => { // single table.dropIndex('column_one') // multi-column table.dropIndex(['column_two', 'column_three']) // custom named table.dropIndex(['column_four'], 'custom_index_name') }) } }Copied!0
-
-
One thing I'm curious about is why we don't specify timestamps on the BaseModel. And the same for migrations - we always duplicate table.timestamp. Is it not worth spending time on (extracting common parts)?
1-
Responding to inox
-
Responding to inox
Sorry for the delayed response!! Yes, if you'd like, you can definitely use mixins to extract those out of your models into a reusable bit of code. That would look very similar to what we do in the next lesson with our organization!
Personally, I never bother to do this with my timestamps because when we use the Ace CLI to create our migrations & models those timestamps come with that stub automatically, so it is actually more work to extract them than it is to just leave them be. Plus, they're consistent enough to be easily updated across the board with a find/replace if needed.
0-
Responding to tomgobich
Yeah, now I see, if it takes more time to extract it's ok to have some duplication. Thank you
1-
Responding to inox
-
-
-
-