【问题标题】:Is it possible to use custom attributes as criteria in my query是否可以在我的查询中使用自定义属性作为条件
【发布时间】:2014-05-16 03:57:03
【问题描述】:

我想知道,是否可以在sails 中使用自定义属性来查询某些记录? 也许我下面的例子会更好地解释它。

模型/User.js

 attributes: { first_name: 'string', last_name: 'string' }

模型/ModelA.js

 attributes: {
  user: {model: 'User'},
  studentName: function(){ return this.user.first_name + " " this.user.last_name },
  ....
 }

我的查询

ModelA.find({studentName: {contains: searchKeyword }}).populate('user').then(console.log);

提前谢谢各位。

【问题讨论】:

    标签: node.js sails.js waterline


    【解决方案1】:

    不,Waterline 不会在查询期间评估实例方法。在评估标准时,它也无法访问填充的模型;即this.user 将为空。您需要执行不带studentName 属性的find,然后自己过滤结果:

    ModelA.find().populate('user').exec(function(err, models) {
    
        models = _.where(models, function(model) {
            return model.studentName().match(searchKeyword);
        }
    
    });
    

    如果这是一个真实的例子,最好搜索 User 模型,填充 ModelA

    User.find(
        {or: [
            {firstName: {contains: searchKeyword}}, 
            {lastName: {contains: searchKeyword}}
        ]}
    ).populate('modela').exec(...)
    

    【讨论】:

      猜你喜欢
      • 2022-08-08
      • 2016-12-09
      • 2022-12-17
      • 2011-06-08
      • 2018-05-26
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多