0

使用配方类型的应用程序,我正在处理路由/端点/后端。团队在到达 GET 请求时需要以下 JSON 结构。

const fakeDataRecipes = [
    {
        id:0,
        title:"PBJ",
        source:"Mother",
        ingredients:["bread", "peanut butter", "jam"],
        instructions: "1. Get bread. 2. Get peanut butter and jam. 3. Put together.",
        category:["snack", "dinner", "vegetarian", "sandwich"],
        user_id:1
    }, 
    {
        id:1,
        title:"Peanut Butter and Banana Sandwich",
        source:"Uncle Steve",
        instructions: "1. Get bread. 2. Get peanut butter. 3. Slice banana. 4. Put together",
        ingredients:["bread", "peanut butter", "banana", "chocolate"],
        category:["snack", "dinner", "vegetarian", "sandwich"],
        user_id:2
    }
];

我已经搜索过,但我似乎 SQLITE3 不支持列中的数组。这种情况的最佳方法是什么?我需要成分和类别作为数组。有人说为成分和类别创建一个新表。其他人说在我不熟悉的 SQLite3 中使用 blob 数据类型。或者将其存储为字符串,然后将其转换为数组,我不确定它是否会起作用或给前端带来问题。以下是knex迁移文件



exports.up = function(knex) {

  return knex.schema.createTable('recipes', recipeColumn=>{

    recipeColumn.increments();
    recipeColumn.text('title').unique().notNullable();
    recipeColumn.text('source').unique().notNullable();


  })

};

4

1 回答 1

0

规范化成单独的表格是这里的方法:

`recipes`: (`title`, `source`)
`ingredients`: (`name`)
`recipes_ingredients`: (`recipe_id`, `ingredient_id`, `quantity`)
`categories`: (`name`)
`categories_recipes`: (`recipe_id`, `category_id`)

举个简单的例子,为每个配方拉取成分数组:

knex.select('name')
  .from('ingredients')
  .join('recipes_ingredients')
  .on('recipes_ingredients.ingredient_id', '=', 'ingredients.id')
  .where('recipes_ingredients.recipe_id', recipeId)

(未经测试,但它看起来像那样)。换句话说,使用连接表作为粘合剂来检索您所追求的结果。

哦,另请参阅此答案

于 2019-07-14T09:14:58.397 回答