2014-04-19 60 views
0

我在我的數據庫中有一個複合鍵。但是在提交表單時出現錯誤。我知道爲什麼由於重複到主鍵而發生錯誤。但我不知道我怎麼會在laravel 4.修復它下面是模式複合鍵驗證在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')); 
     }); 

這裏是model.I've已經使用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]:完整性約束違規:用於密鑰 'lecture_delegates_lecture_id_delegate_id_unique' 1062重複條目 '1-4'(SQL:插入lecture_delegateslecture_iddelegate_idupdated_atcreated_at)值(1,4,2014-04 -19 08:22:37,2014-04-19 08:22:37))

回答

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'));