当帆默认模型属性获得其值时?

时间:2019-01-22 13:29:59

标签: node.js model sails.js

当帆填充了我们在config/models.js上添加的默认全局属性时, 默认设置如下:

attributes: {
  id: { type: 'number', autoIncrement: true },
  createdAt: { type: 'number', autoCreatedAt: true },
  updatedAt: { type: 'number', autoUpdatedAt: true },
}

现在,如果我们向此默认属性中添加诸如creatorId之类的东西,我们该如何为所有models填充一次?

attributes: {
  id: { type: 'number', autoIncrement: true },
  createdAt: { type: 'number', autoCreatedAt: true },
  updatedAt: { type: 'number', autoUpdatedAt: true },
  creatorId: { type: 'number'}
}

此更改后,所有模型的creatorId的值均为0,如何在保存之前将userId设置为所有模型creatorId而不重复我的自我? / p>

1 个答案:

答案 0 :(得分:3)

在控制器中,您正在数据库中创建条目,这应该很简单。假设您有两个模型,User(带有Sails内置身份验证)和Thing(某人可以拥有)。

Thing模型中,我将ownerId更改为owner并将其与User模型关联,如下所示:

attributes: {
    id: { ... },
    createdAt: { ... },
    updatedAt: { ... },
    owner: {
        model: 'User',
        required: yes      // Enable this when all the stuff in the db has this set
    },
}

如果您知道数据库术语,这将创建关联或一对多关系。

现在在控制器中用于创建要插入对象的位置:

Thing.create({
  someAttribute: inputs.someValue,
  someOtherAttribute: inputs.someOtherValue,
  owner: this.req.me.id
});

如果您想立即使用创建的对象,可以将.fetch()附加到链.create({...})之后,如下所示:

var thing = await Thing.create({ ... }).fetch();

让我知道是否有不清楚的地方。

我实际上建议您投资9美元购买SailsJS课程。这是一门官方课程,由SailsJS的创建者Mike McNeil教授。从npm i sails -g开始,您需要在Heroku云平台上投入生产。它使用MailGun,Stripe付款等等,教授基本的Vue(帆伞风味)。他们链接到网站here

上的课程

更新

进行了一些进一步的挖掘,并受到了一些类似案例的启发。

您可以做的是使用包含.create()方法的自定义方法扩展模型。此方法可以从您的控制器接收请求对象,但是这样做比以前的建议要复杂,而不是仅向现有调用中添加ownerId: this.req.me.id,。无论如何,我都会示范。

// Your model
module.exports = {
    attributes: { ... },
    proxyCreate(req, callback) {
        if(!req.body.ownerId){
            req.body.ownerId = req.me.id     // or req.user.id, cant remember 
                                             // which works here
        }
        Thing.create(request.body, callback);
    }
}

在您的控制器中:

...
// Change from:
Thing.create(req.body);

// To:
Thing.proxyCreate(req);
...

更新#2

我的另一个想法是在每个路由的基础上添加中间件。我不知道您的路线的复杂性,但是您只能为这些路线创建自定义中间件。

router.js中,您可以编辑路线(为简便起见,我将显示一条路线):

....
'POST /api/v1/things/upload-thing': [
        { action: 'helpers/add-userid-to-ownerid' },
        { action: 'new-thing' }
],
....

helpers/add-userid-to-ownerid中:

module.exports: {
    fn: function(req, res) {
        if(!req.body.ownerId){
            req.body.ownerId = req.me.id;
        }
    }
}
相关问题