This package extends AdonisJS Lucid model to facilitate internationalization of database entities.
Install the package with the following NPM command:
npm install @ungonnak/intldb
This package enforces the use of an extra table for each internationalized entity of the database.
So, for example, you have two tables projects
, project_types
, you'll need to create projects_translations
and
project_types_translations
to accommodate the properties that needs translation.
-
Add the provider to your
start/app.js
file:const providers = [ // ... "@ungonnak/adonisjs-intldb/providers/IntldbProvider", // ... ];
-
Add the middleware to
globalMiddleware
section of yourstart/kernel.js
file:const globalMiddleware = [ // ... "Ungonnak/Intldb/Middleware/LocalizeDatabase", // ... ];
-
Create a migration to the
languages
table:"use strict"; const Schema = use("Schema"); class LanguagesSchema extends Schema { up() { this.create("languages", (table) => { table.string("name"); table.string("code").primary(); table.timestamps(false, true); }); } down() { this.drop("languages"); } } module.exports = LanguagesSchema;
-
Add the languages that you want to support in your project.
-
Create a model that extends the
LocalizedModel
class, in this exampleProjectType
:"use strict"; const LocalizedModel = use("LocalizedModel"); class ProjectType extends LocalizedModel { } module.exports = ProjectType;
-
Create the migration for the
project_types
table:"use strict"; const Schema = use("Schema"); class ProjectTypesSchema extends Schema { up() { this.create("project_types", (table) => { table.increments().unsigned(); table.timestamps(false, true); }); } down() { this.drop("project_types"); } } module.exports = ProjectTypesSchema;
-
And the migration for the international info for the
project_types
table:"use strict"; const Schema = use("Schema"); class ProjectTypesTranslationSchema extends Schema { up() { this.create("project_types_translations", (table) => { table.increments().unsigned(); table.integer("project_type_id").unsigned(); table.string("language_code"); table.string("name"); table.timestamps(false, true); table.foreign(["project_type_id", "language_code"]) .onDelete("CASCADE") .onUpdate("RESTRICT") .references(["project_types.id", "languages.code"]); }); } down() { this.drop("project_types_translations"); } } module.exports = ProjectTypesTranslationSchema;
-
Use the model class like you aways used, but remember that the language that will be used is defined by the
LocalizeDatabase
middleware. If you, for some reason, need to change the language, change thecurrentLocale
of theLocalizedModel
class like this:LocalizedModel = use ("LocalizedModel"); // ... LocalizedModel.currentLocale = "fr"; // Do some stuff in the french records LocalizedModel.currentLocale = "en"; // Do some stuff in the english records // ...
- 0.2.0 - Initial release
- 0.2.1 - Fix inserts bug