繁体   English   中英

如何使用Knex.js查询关系?

[英]How to query relations with Knex.js?

我正在做一个Node.js REST API教程。 我使用Express,Knex.js(0.19.0)和PostgreSQL。

我有两个数据库表, users

// user_migration.js

exports.up = function(knex) {
  return knex.schema.createTable('users', function(table) {
    table
      .increments('id')
      .primary()
      .unsigned();
    table.string('firstName');
    table
      .string('lastName')
      .index()
      .notNullable();
    table
      .string('email')
      .unique()
      .index()
      .notNullable();
    table.string('password').notNullable();
    table.string('role').defaultTo('STAFF');
    table.boolean('isActive').defaultTo(false);
    table.timestamp('createdAt').defaultTo(knex.fn.now());
    table.timestamp('updatedAt').defaultTo(knex.fn.now());
  });
};

posts

// post_migration.js

exports.up = function(knex) {
  return knex.schema.createTable('posts', function(table) {
    table
      .increments('id')
      .primary()
      .unsigned();
    table.string('title').notNullable();
    table.text('body');
    table.boolean('published').defaultTo(false);
    table
      .integer('author')
      .unsigned()
      .index()
      .references('id')
      .inTable('users')
      .onDelete('SET NULL');
    table.timestamp('createdAt').defaultTo(knex.fn.now());
    table.timestamp('updatedAt').defaultTo(knex.fn.now());
  });
};

我想在http://localhost:8081/users/1/posts发出GET请求,以显示user.id 1的帖子。

// user_get.js

  async getPosts(req, res, next) {
    try {
      // Check if user exists
      const user = await this.knex('users')
        .where('id', req.params.id)
        .first();

      // If not, return NOT FOUND status code
      if (!user) return next(createError(404, 'User not found'));

      /**
       * Right here, I am not sure if I am doing it right.
       */
      // Get from database and filter
      const result = await this.knex('users')
        .join('posts', 'posts.author', '=', 'users.id')
        .select()
        .then(posts => posts.filter(post => post.author === user.id));

      // Return OK status code and related posts
      res.status(200).send(result);
    } catch (error) {
      // Return BAD REQUEST status code
      return next(createError(400, error);
    }
  }

我期望的是属于用户1的一系列帖子:

[
    {
        "id": 1,
        "title": "Number One Post",
        "body": "This is the one body",
        "published": true,
        "author": 1,
        "createdAt": "2019-07-23T06:14:04.281Z",
        "updatedAt": "2019-07-23T06:14:04.281Z"
    },
    {
        "id": 2,
        "title": "Number Two Post",
        "body": "This is two body",
        "published": false,
        "author": 1,
        "createdAt": "2019-07-23T06:14:04.281Z",
        "updatedAt": "2019-07-23T06:14:04.281Z"
    }
]

但是我是这样的:

[
    {
        "id": 1,
        "firstName": "Some",
        "lastName": "One",
        "email": "some@one.com",
        "password": "password789",
        "role": "STAFF",
        "isActive": false,
        "createdAt": "2019-07-23T06:14:04.281Z",
        "updatedAt": "2019-07-23T06:14:04.281Z",
        "title": "Number One Post",
        "body": "This is the one body",
        "published": true,
        "author": 1
    },
    {
        "id": 2,
        "firstName": "Some",
        "lastName": "One",
        "email": "some@one.com",
        "password": "password789",
        "role": "STAFF",
        "isActive": false,
        "createdAt": "2019-07-23T09:21:34.285Z",
        "updatedAt": "2019-07-23T09:21:34.285Z",
        "title": "Number Two Post",
        "body": "This is two body",
        "published": false,
        "author": 1
    }
]

如何在不了解用户信息的情况下查询用户1的帖子? 请帮忙。

PS updatedAt中的updatedAt也无法正常工作。 当我更新时,它不会更新时间戳。 我该如何解决?

只需在第二个查询中删除对用户的加入

         const result = await this.knex('posts')
        .where('posts.author', user.id)
        .select()


      // Return OK status code and related posts
      res.status(200).send(result);

暂无
暂无

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

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