我的数据库中有一个复合键。但是在提交表格时我收到了错误。我知道为什么错误发生是因为主键重复。但我不知道如何在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重复条目&#39; 1-4&#39; for key&#39; lecture_delegates_lecture_id_delegate_id_unique&#39; (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))
答案 0 :(得分:0)
如果要为表创建复合主键,则需要在创建该表时指定。
请查看official documentation regarding indexes
在你的情况下,它将是:
Schema::create('lecture_delegates', function($table){
$table->increments('id');
$table->integer('lecture_id');
$table->integer('delegate_id');
$table->timestamps();
$table->primary(array('lecture_id', 'delegate_id'));
$table->unique(array('lecture_id', 'delegate_id'));
});
请注意$table->primary(array('lecture_id', 'delegate_id'));