Laravel 5.1中的复合键验证

时间:2015-12-14 16:41:18

标签: php laravel-5 laravel-5.1

我在Laravel 5.1中尝试以下查询

Select * from tblSubCategory 
Where SubCategoryID != 1 and CategoryID = 1 and SubCategory = 'test data';

以下是我在Laravel中的代码

$v = \Validator::make($request->all(), [
    'SubCategory' => 'required|max:100|min:5|unique:tblsubcategory,SubCategory,'
        .''.$request->input('CategoryID')
        .',CategoryID,SubCategoryID,'.$request->input('SubCategoryID')

]);

以上表达式产生以下查询。

select count(*) as aggregate from `tblsubcategory` 
where `SubCategory` = 'under website1' and `CategoryID` <> 1 and `SubCategoryID` = 1

唯一键

UNIQUE KEY `UK_tblSubCategory_SubCategory_CategoryID` (`CategoryID`,`SubCategory`);

1 个答案:

答案 0 :(得分:1)

方法:1:与Laravel兼容:5。*

在命令行composer require felixkiss/uniquewith-validator:2.*

将以下内容添加到providers array中的 config/app.php

'providers' => array(
    'Felixkiss\UniqueWithValidator\UniqueWithValidatorServiceProvider',
),

$v = \Validator::make($request->all(), [
    'SubCategory' => 'required|max:100|min:5|unique_with:tblsubcategory,CategoryID',
    'CategoryID' => 'required',
]);

方法:2

$v = \Validator::make($request->all(), [
    'SubCategory' => 'unique:tblsubcategory,SubCategory,'
                     .$request->input('SubCategoryID') 
                     .',SubCategoryID,CategoryID,'
                     .$request->input('CategoryID')
]);

if ($v->fails()) {
    return \Redirect::back()
                ->withErrors($v)
                ->withInput();
}