【问题标题】:Composite key validation in laravel 4laravel 4 中的复合键验证
【发布时间】:2014-04-19 19:32:54
【问题描述】:

我的数据库中有一个复合键。但是在提交表单时出现错误。我知道为什么由于主键重复而发生错误。但我不知道如何在 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 键“lecture_delegates_lecture_id_delegate_id_unique”的重复条目“1-4”(SQL:插入lecture_delegateslecture_iddelegate_idupdated_atcreated_at)值 (1, 4, 2014-04-19 08:22:37, 2014-04-19 08:22:37))

【问题讨论】:

    标签: laravel


    【解决方案1】:

    如果要为表创建复合主键,则需要在创建该表时指定。

    请看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-&gt;primary(array('lecture_id', 'delegate_id'));

    【讨论】:

      猜你喜欢
      • 2021-09-30
      • 2021-09-16
      • 2013-05-07
      • 2014-03-09
      • 2021-05-18
      • 2013-12-25
      • 2013-09-09
      • 2015-06-28
      • 1970-01-01
      相关资源
      最近更新 更多