【问题标题】:Adonis JS - Access Model's custom methodAdonis JS - 访问模型的自定义方法
【发布时间】:2020-02-19 13:51:27
【问题描述】:

我向模型添加了一个名为 customMethod 的自定义方法,如下所示:

class Prize extends Model {

  customMethod(){

    return 'test'

  }

}

当我使用find通过主键获得奖品时,我可以调用这个方法没有问题

    const prize = await Prize.find(1);

    return prize.customMethod();
    //returns 'test'

但是,如果我以任何其他方式获得奖品,通过关系或通过字段查询,我无法访问此方法。

   const countrysPrizes = await country.prizes().fetch();

    for (const key in countrysPrizes) {
      if (countrysPrizes.hasOwnProperty(key)) {
        const prize = countrysPrizes[key];

        return prize.customMethod();
        //returns 500 - prize.customMethod is not a function
      }
    }

如何在遍历多个对象时访问此方法?

【问题讨论】:

    标签: adonis.js


    【解决方案1】:

    您需要使用<fetched_object>.rows,因为VanillaSerializer

    示例代码:

      const user = await User.find(1);
      const posts = await user.posts().fetch();
    
      posts.rows.forEach(post=> { // use .rows
        console.info(post.customMethod()); // Your custom method
      });
    

    我在使用基本的foreach 循环时遇到了麻烦。所以我用.foreach()

    fetch() 的输出示例:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多