【问题标题】:Laravel validation exists where NOTLaravel 验证存在于不存在的地方
【发布时间】:2013-12-26 13:11:02
【问题描述】:

基于documentations。 Exists 可以有 4 个参数:

exists:table,id,where,0

问题是,如果我希望它出现在不存在的地方怎么办。比如哪里不是0。

$validator = Validator::make(
    array(
        'groups' => $groups
    ),
    array(
        'groups' => 'required|exists:groups,jid,parent,!=,0'
    )
);

【问题讨论】:

  • 您可以使用自定义验证。 laravel.com/docs/validation#custom-validation-rules
  • 我正在尝试调查它。再次感谢@Anam。不过对 php 有点陌生。
  • @Anam 我似乎不明白自定义验证是如何工作的,以及如何在存在的情况下实现它。

标签: php laravel eloquent


【解决方案1】:

你可以使用unique

示例

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

在上述规则中,只有 account_id 为 1 的行才会包含在唯一检查中。

http://laravel.com/docs/4.2/validation#rule-unique

【讨论】:

  • 这与接受的答案基本相同,除了它已经准备好与 Laravel 一起使用,而且它还有一个额外的好处是可以定义一个被忽略的 id,这对更新特别有用。
  • 当最好的答案不是公认的答案时,这令人失望。谢谢。
【解决方案2】:

你可以这样使用:

Validator::extend('not_exists', function($attribute, $value, $parameters)
{
    return DB::table($parameters[0])
        ->where($parameters[1], '=', $value)
        ->andWhere($parameters[2], '<>', $value)
        ->count()<1;
});

【讨论】:

  • 看下面完全矫枉过正
【解决方案3】:

使用 Laravel 5.2 或更高版本,您可以在要检查的值前面加上 !

'groups' => 'required|exists:groups,jid,parent,!0'

unique 的登录方式相同,只是你需要额外的参数:

'groups' => 'required|unique:groups,jid,NULL,id,parent,!0'

【讨论】:

  • 它就像:存在:(表名),(列名)......然后我迷路了。你可以解释吗?官方文档在这件事上没有帮助我。
  • 如果你使用 Laravel Degubar 包,你实际上可以检查每个请求中触发了哪些查询,这样你就可以看到你的验证规则对数据库做了什么。也就是说,文档中很好地涵盖了存在规则:exists:(table name),(column name),[(column name of additional query), (value of column for additional query with optional !)]
  • 这很奇怪,如果它是一个字符串字段,其值实际上以! 开头?
【解决方案4】:

我知道您正在寻找“非 0”,但为了参考,您可以使用 NOT_NULL,如下所示:

'groups' => 'required|exists:groups,jid,parent,NOT_NULL'

它现在没有在文档中列出,但是here is the discussion about it (see very last post)

【讨论】:

    【解决方案5】:

    这里有一个自定义验证器

    Validator::extend('not_exists', function($attribute, $value, $parameters, $validator)
    {
        $table = array_shift($parameters);
        $db    = \DB::table($table);
    
        foreach ($parameters as $parameter)
        {
            $check = explode(';', $parameter);
            $col   = array_shift($check);
            $value = array_get($check, 0, array_get($validator->getData(), $col, false));
    
            $db->where($col, $value);
        }
    
        return $db->count() < 1;
    });   
    

    示例用法:

    not_exists:model_has_roles,role_id,model_type;App\User,model_id
    

    你可以像这样传递默认值:

    model_type;App\User
    

    【讨论】:

      【解决方案6】:

      也许你可以试试&lt;&gt; 0,那是SQL表示不相等

      【讨论】:

        猜你喜欢
        • 2018-01-29
        • 2014-09-04
        • 1970-01-01
        • 2018-10-12
        • 1970-01-01
        • 2018-11-27
        • 1970-01-01
        • 2017-10-04
        • 2014-10-02
        相关资源
        最近更新 更多