【问题标题】:combination columns in validationRule验证规则中的组合列
【发布时间】:2019-07-26 08:41:23
【问题描述】:

我是 Adonis.js 的新手,我有这样的用户迁移:

  table.enu('type', ['client','admin','super_admin']),
  table.string('mobile', 80).notNullable().unique();

现在,我想检查 mobile + type 在验证中对所有用户是否唯一,而我只能使用此代码检查移动设备唯一性:

mobile : 'required|string|unique:users,mobile',

我怎么能这样?

【问题讨论】:

    标签: validation adonis.js


    【解决方案1】:

    我使用扩展验证器创建了类似的东西:

    async unique_combinationFn(data, field, message, args, get) { // eslint-disable-line
    const Database = use('Database');
    const value = get(data, field);
    if (!value) {
      return;
    }
    const [table, ...columns] = args;
    
    const multipleClauses = columns.reduce(
      (oldObject, column) => ({
        ...oldObject,
        [column]: data[column],
      }),
      {}
    );
    
    const where = { ...multipleClauses, [field]: value };
    
    const row = data.id
      ? await Database.table(table)
          .where(where)
          .whereNot('id', data.id)
          .first()
      : await Database.table(table)
          .where(where)
          .first();
    if (row) {
      throw message;
    }
    

    }

    并使用:

    code: [rule('required'), rule('unique_combination', ['users', 'company_id'])],
    

    您可以在此链接的文档中找到更多信息:

    Extending Validator

    【讨论】:

      【解决方案2】:

      使用 Adonis.js 自己的验证器是不可能的。您应该为这种用例编写自己的验证方法。

      在这里查看 Adonisjs 创始人对此的回复:https://forum.adonisjs.com/t/several-unique-fields/1430/3

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-15
        • 2021-05-18
        • 1970-01-01
        • 1970-01-01
        • 2017-07-09
        • 1970-01-01
        • 2018-04-23
        相关资源
        最近更新 更多