简体   繁体   中英

How to save an array using AdonisJs migrations?

I'm trying to save an array to a PostgreSQL database, but I can't!

 'use strict' const Schema = use('Schema'); class UsersSchema extends Schema { up () { this.create('users', (table) => { table.increments(); table.string('name', 255).notNullable(); table.string('languages', 255).notNullable().defaultTo('[]'); table.timestamps(); }); } down () { this.drop('users'); } } module.exports = UsersSchema;

I tried to save like a string, like an array and use JSON.parse(), but it doesn't work

First of all your datatype is wrong, Adonisjs provides "json" datatype for a particular column. Solution:-

  1. Change column type from string -> JSON

  2. In the model, set datatype of "types" column as "string"

  3. How to write a query?

    a) You need to use a seeder to insert the data

    b) You have to write beforeSave() hook, and then using JSON.stringify() stringify your "types" so that the database can accept it.

    c) To retrieve data, write afterFetch() and afterFind() hook to parse your JSON string to normal JSON.

You should be looking for seeding rather than migration if you intend to insert data

Once you've prepared your database schema with migrations, the next step is to add some data. This is where database seeds and factories come into the picture.

read more here: https://adonisjs.com/docs/4.1/seeds-and-factories

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM