简体   繁体   English

如何使用 AdonisJs 迁移保存数组?

[英]How to save an array using AdonisJs migrations?

I'm trying to save an array to a PostgreSQL database, but I can't!我正在尝试将数组保存到 PostgreSQL 数据库,但我做不到!

 '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我尝试像字符串一样保存,像数组一样保存并使用 JSON.parse(),但它不起作用

First of all your datatype is wrong, Adonisjs provides "json" datatype for a particular column.首先你的数据类型是错误的,Adonisjs 为特定列提供了“json”数据类型。 Solution:-解决方案:-

  1. Change column type from string -> JSON从字符串更改列类型 -> JSON

  2. In the model, set datatype of "types" column as "string"在 model 中,将“types”列的数据类型设置为“string”

  3. How to write a query?如何编写查询?

    a) You need to use a seeder to insert the data a) 您需要使用播种机来插入数据

    b) You have to write beforeSave() hook, and then using JSON.stringify() stringify your "types" so that the database can accept it. b) 你必须编写beforeSave()钩子,然后使用JSON.stringify()将你的“类型”字符串化,以便数据库可以接受它。

    c) To retrieve data, write afterFetch() and afterFind() hook to parse your JSON string to normal JSON. c) 要检索数据,编写afterFetch()afterFind()钩子以将 JSON 字符串解析为正常的 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在此处阅读更多信息: https : //adonisjs.com/docs/4.1/seeds-and-factories

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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