使用相关模型的数量扩展模型

Extend model with count of related model

我正在尝试构建一个带有环回的简单博客。我想用评论的数量来扩展 get Posts。

我脑子里有两种可能的方法。 1) 通过评论数来扩展 get-posts 的响应,这是我最喜欢的方式,但我不知道如何扩展 reposne。 2)我试图观察评论保存并获取帖子模型,但我无法更改它。

post.json

{
  "name": "post",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "title": {
      "type": "string",
      "required": true
    },
    "content": {
      "type": "string",
      "required": true
    }
    "published": {
      "type": "boolean",
      "required": true,
      "default": false
    }
    "commentCount": {
      "type": "number",
      "default": 0
    }
  },
  "validations": [],
  "relations": {
    "user": {
      "type": "belongsTo",
      "model": "user",
      "foreignKey": ""
    },
    "comments": {
      "type": "hasMany",
      "model": "comment",
      "foreignKey": ""
    }
  },
  "acls": [
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "DENY"
    },
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "admin",
      "permission": "ALLOW"
    },
    {
      "accessType": "EXECUTE",
      "principalType": "ROLE",
      "principalId": "admin",
      "permission": "ALLOW",
      "property": "find"
    },
    {
      "accessType": "EXECUTE",
      "principalType": "ROLE",
      "principalId": "$authenticated",
      "permission": "ALLOW",
      "property": "create"
    },
    {
      "accessType": "READ",
      "principalType": "ROLE",
      "principalId": "$owner",
      "permission": "ALLOW"
    },
    {
      "principalType": "ROLE",
      "principalId": "$authenticated",
      "permission": "ALLOW",
      "property": [
        "__create__comments",
        "__get__comments"
      ]
    },
    {
      "principalType": "ROLE",
      "principalId": "$owner",
      "permission": "ALLOW",
      "property": "__delete__comments"
    }
  ],
  "methods": {}
}

comment.json

{
  "name": "comment",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "content": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "user": {
      "type": "belongsTo",
      "model": "user",
      "foreignKey": ""
    },
    "idea": {
      "type": "belongsTo",
      "model": "post",
      "foreignKey": ""
    }
  },
  "acls": [
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "DENY"
    },
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "admin",
      "permission": "ALLOW"
    },
    {
      "accessType": "READ",
      "principalType": "ROLE",
      "principalId": "$authenticated",
      "permission": "ALLOW"
    },
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$owner",
      "permission": "ALLOW"
    }
  ],
  "methods": {}
}

comment.js##

var loopback = require('loopback');

module.exports = function(Comment) {
    Comment.observe('after save', function(ctx, userInstance, next) {
      var postId = ctx.instance.postId;

// loopback.getModel('post').definition.rawProperties.commentCount... something... something... 

    });
};

我对环回还是很陌生,我不知道实现解决方案的最佳方法是什么。也许您有第三种更好的方法?或者谁能​​帮我完成 comment.js.

首先,在您的 comment.json 中,您写的是 idea 而不是 post:

 "post": {  //change here
      "type": "belongsTo",
      "model": "post",
      "foreignKey": ""
    }

其次,您只需在 post 中添加一个 commentCount 链接到您在 after save 方法中的评论,然后更新 post 的属性:

'use strict';

var app = require('../../server/server');
var models = app.models;
var Post;
// pattern to get your models on start event
app.on('started', function () {
    Post = models.post;
});

module.exports = function(Comment) {
   Comment.observe('after save', function(ctx, next) {
      // only add a commentCount if it's a new instance
      if (ctx.instance && ctx.isNewInstance && ctx.instance.postId) {
          Post.findOne({where: {id: ctx.instance.postId}}, function (err, post) {
              if (!err) {
                 post.updateAttributes({commentCount: post.commentCount++});
              }
          });
      }
      next();
   });
};

另一种解决方案是在 post.js 文件中创建一个 customGet 端点:

'use strict';
 module.exports = function(Post) {
        Post.customGet = function (postId, cb) {
            Post.findOne({where: {id: postId}, include: 'comments'}, function (err, post) {
                if(err){
                    return cb(err, {});
                }
                post.commentCount = post.comments.length;
                return cb(err, post);
            });
        }

        Post.remoteMethod('customGet', {
            description: 'New endpoint with the commentCount',
            accepts: {arg: 'postId', type: 'string'},
            returns: {arg: 'post', type: 'object'},
            http: {verb: 'get'}
        });
  };

你可以稍微改进一下这个方法,但你明白了。