【问题标题】:Laravel validation: unique rule 4th parameterLaravel 验证:唯一规则第 4 个参数
【发布时间】:2015-02-03 21:10:41
【问题描述】:

查看 Laravel 文档、API 文档和源代码,我想知道是否有人知道以下唯一规则中的第四个参数 id 的用途?

'email' => 'unique:users,email_address,NULL,id,account_id,1'

我目前对这条规则的理解是:

  • users - 看这张表
  • email_address - 检查此列
  • NULL - 我们可以指定要忽略的主键/ID 值,但我们没有打扰,所以这个参数基本上被忽略了
  • id - 不确定
  • account_id - 附加 where 子句,这是列名
  • 1 - where 子句中 account_id 的值

文档:http://laravel.com/docs/4.2/validation

函数负责执行\Illuminate\Validation\Validator 中函数validateUnique($attribute, $value, $parameters) 在线949 中的唯一规则验证:

/**
 * Validate the uniqueness of an attribute value on a given database table.
 *
 * If a database column is not specified, the attribute will be used.
 *
 * @param  string  $attribute
 * @param  mixed   $value
 * @param  array   $parameters
 * @return bool
 */
protected function validateUnique($attribute, $value, $parameters)
{
    $this->requireParameterCount(1, $parameters, 'unique');

    $table = $parameters[0];

    // The second parameter position holds the name of the column that needs to
    // be verified as unique. If this parameter isn't specified we will just
    // assume that this column to be verified shares the attribute's name.
    $column = isset($parameters[1]) ? $parameters[1] : $attribute;

    list($idColumn, $id) = array(null, null);

    if (isset($parameters[2]))
    {
        list($idColumn, $id) = $this->getUniqueIds($parameters);

        if (strtolower($id) == 'null') $id = null;
    }

    // The presence verifier is responsible for counting rows within this store
    // mechanism which might be a relational database or any other permanent
    // data store like Redis, etc. We will use it to determine uniqueness.
    $verifier = $this->getPresenceVerifier();

    $extra = $this->getUniqueExtra($parameters);

    return $verifier->getCount(

        $table, $column, $value, $id, $idColumn, $extra

    ) == 0;
}

干杯

【问题讨论】:

    标签: php laravel-4 laravel-validation


    【解决方案1】:

    啊,疯了,我想一分钱刚刚掉了。

    如果我错了,请纠正我,但是第 4 个参数与第 3 个参数相关,因为它允许我们在忽略 3 中指定的 ID 时指定要检查的列。如果不是id

    例如,如果主键不是id,而是user_id,我们可以这样做:

    'email' => 'unique:users,email_address,NULL,user_id,account_id,1'
    

    【讨论】:

      【解决方案2】:

      你是对的,第 4 个参数是 id 的列名,如果与 'id' 不同,如下所示:

      https://github.com/laravel/framework/blob/4.2/src/Illuminate/Validation/Validator.php#L991

      【讨论】:

        【解决方案3】:
        • $ARG1 - 查看此表
        • $ARG2 - 检查此列。默认为验证密钥(eq:电子邮件)
        • $ARG3 - 附加的 WHERE NOT 值。
        • $ARG4 - 额外的 WHERE NOT 字段。默认为主键
        • $ARG5 - 附加 WHERE 字段 1 - 附加 WHERE 值。

        【讨论】:

          猜你喜欢
          • 2015-02-27
          • 2018-05-24
          • 1970-01-01
          • 2016-04-08
          • 2016-08-03
          • 2019-11-15
          • 2020-09-13
          • 2018-07-10
          • 2013-07-01
          相关资源
          最近更新 更多