簡體   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