我的数据库中有一个复合键 . 但是在提交表格时我收到了错误 . 我知道为什么错误发生是因为主键重复 . 但我不知道如何在laravel 4中修复它 . 这是架构
Schema::create('lecture_delegates', function($table){
$table->increments('id');
$table->integer('lecture_id');
$table->integer('delegate_id');
$table->timestamps();
$table->unique(array('lecture_id', 'delegate_id'));
});
这是模型 . 我已经使用了felixkiss,但它不起作用 .
class LectureDelegate extends BaseModel
{
public static $unguarded = true;
protected $table = 'lecture_delegates';
public static $rules = array(
'lecture_id' => 'required|unique_with:lecture_delegates, delegate_id',
'delegate_id' => 'required'
);
}
和控制器:
class LectureDelegatesController extends BaseController {
public function create()
{
$validation = Lecture::validate(Input::all());
$lecture_id = Input::get('lecture_id');
$delegate_id = Input::get('delegate_id');
if ($validation->fails()) {
return Redirect::to('lecture', $lecture_id)->withErrors($validator)->withInput();
}else {
LectureDelegate::create(array(
'lecture_id' => Input::get('lecture_id'),
'delegate_id'=> Input::get('delegate_id')
));
return Redirect::to('/')->with('message', 'Your are successfully apply to the lecture');
}
}
}
形式:
{{ Form::open(array('route' =>'create_lecture_delegate', 'method' =>'POST')) }}
{{ Form::hidden('lecture_id', $lecture->id) }}
{{ Form::hidden('delegate_id', Auth::user()->id) }}
<p>{{ Form::submit('Apply') }}</p>
{{ Form::close() }}
当我尝试提交表单时显示此错误消息 .
SQLSTATE [23000]:完整性约束违规:1062重复项'1-4'用于键'lecture_delegates_lecture_id_delegate_id_unique'(SQL:插入 lecture_delegates
( lecture_id
, delegate_id
, updated_at
, created_at
)值(1,4,2014-04-19 08:22:37,2014-) 04-19 08:22:37))
1 回答
如果要为表创建复合主键,则需要在创建该表时指定 .
请看一下official documentation regarding indexes
在你的情况下,它将是:
注意
$table->primary(array('lecture_id', 'delegate_id'));