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'

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

报告相同问题?

悬赏问题

  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题