【发布时间】:2016-01-07 17:58:57
【问题描述】:
我的规则如下。请检查以下代码中的composite_unique
public function rules()
{
return [
'SubCategory' => 'required|max:25|min:5|composite_unique:tblsubcategory,CategoryID',
'CategoryID' => 'required|min:1'
];
}
我的更新方法如下...
public function update(SubCategoryRequest $request)
{
$SubCat = $this->CacheCollection->getAllSubCategories($request->input('CategoryID'));
$SubCategory = $SubCat->SubCategories->where('SubCategoryID', 1)->first();
$SubCategory->SubCategory = $request->input('SubCategory');
$SubCategory->CategoryID = $request->input('CategoryID');
$SubCategory->save();
}
我的 Validator 类如下所示。请检查以下代码中的composite_unique 规则。
class ValidationServiceProvider extends ServiceProvider
{
public function boot() {
$this->app['validator']->extend('composite_unique',
function ($attribute, $value, $parameters, $validator) {
// remove first parameter and assume it is the table name
$table = array_shift( $parameters );
// start building the conditions
$fields = [ $attribute => $value ];
while ( $field = array_shift( $parameters ) ) {
$fields[ $field ] = \Request::get( $field );
}
// query the table with all the conditions
$result = \DB::table( $table )
->select( \DB::raw( 1 ) )
->where( $fields )->first();
return empty( $result ); // edited here
});
}
}
有什么问题
当我尝试更新记录并且不编辑任何内容并单击更新按钮时...我收到重复 SubCategory 和 CategoryID 组合的错误。我认为验证代码只是为了在插入新记录之前进行检查。对于更新它不起作用。
下面是子类表的Schema
CREATE TABLE `tblsubcategory` (
`SubCategoryID` int(11) NOT NULL,
`SubCategory` varchar(25) NOT NULL,
`CategoryID` int(11) NOT NULL,
`IsActive` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `tblsubcategory`
MODIFY `SubCategoryID` int(11) NOT NULL AUTO_INCREMENT;
下面是唯一键约束
ALTER TABLE `tblsubcategory`
ADD PRIMARY KEY (`SubCategoryID`),
ADD UNIQUE KEY `UK_tblSubCategory_SubCategory_CategoryID` (`CategoryID`,`SubCategory`);
【问题讨论】:
标签: php laravel-5.1 laravel-5.2