dsbj66959 2015-09-20 06:34
浏览 35
已采纳

laravel验证批次列中的唯一值

I have table that have role column, i have to check and validate for every type need only one manager like this :

| id |   role | type | name 
_______________________________
| 1 | manager | 1    | Pedram 
| 2 | member  | 1    | Parham
| 3 | member  | 2    | Pedram 
| 4 | member  | 1    | Parham

i have to do this with Laravel unique: validation.

i wrote a custom validation and it works :

    public function validateUniqueValue($attribute, $value, $parameters)
{
    $query = DB::table($parameters[0])->where($parameters[1], $value);
    if (array_key_exists(2, $parameters)) {
        $query->where($parameters[2], $parameters[3]);
    }
    if ($query->count() > 0) {
        return false;
    }
    else {
        return true;
    }
}

but, how can i do something like this ?

  • 写回答

1条回答 默认 最新

  • dsft8327 2015-09-20 10:15
    关注

    If you want to validate input for distinct values then you can use unique:tablename constraint in Validator. However we can also add conjunctions in the constraint. So in your example you could do the following:

    $validator = Validator::make
    (
          ['type' => $typeval], 
          ['type' => 'unique:table,role,' . $role_value]
    );
    
    if($validator->fails()) //not distinct role, type pair
    else //distinct
    

    Which would produce the SQL:

    SELECT COUNT(*) FROM `table` WHERE `type` = ? AND `role` = ?
    

    So this will obviously allow all distinct pairs for any role/type and not just manager/type pairs but if you just want to check for distinct manager/type pairs you would need to let $role_value = 'manager'

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献