Laravel 4 - 验证器未找到列错误

时间:2014-08-10 20:24:26

标签: php laravel laravel-4 validation

尝试使用唯一验证规则时,我收到此错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select count(*) as aggregate from `empleados` where `cedula` = asd and `id` <> asd)

这是我的迁移功能:

        Schema::create('empleados', function($table){
            $table->string('cedula');
            $table->string('nombre');
            $table->string('apellido');
            $table->string('sexo');
            $table->timestamps();

            $table->primary('cedula');
        });

这是我的模特:

<?php
    class Empleado extends Eloquent {
        protected $table = 'empleados';
        protected $primaryKey = 'cedula';
        public $errors;
        protected $fillable = array('cedula','nombre','apellido','sexo');


        public function isValid($data,$edit)
        {
            $rules = array(
                'cedula'     => 'required|unique:empleados',
                'nombre' => 'required|max:40',
                'apellido'  => 'required|max:40',
                'sexo' => 'required'
            );

            if($edit){
                $rules['cedula'] .= ',cedula,' . $this->getKey();
            }

            (...)

我认为这是&#34;独特&#34;的错误。验证规则,因为我不知道为什么laravel使用名为&#39; id&#39;当我从未定义那个。

2 个答案:

答案 0 :(得分:2)

只需改变一下:

'cedula'     => 'required|unique:empleados',

为:

'cedula'     => 'required|unique:empleados,cedula',

以后,编辑时,只需添加值忽略

if($edit){
    $rules['cedula'] .= ',' . $this->getKey() . ',cedula';
}

那是因为Laravel这样做了:

  1. 检查列foo
  2. 的值cedula是否唯一
  3. 但忽略值为bar
  4. 的行

    现在,如果您未指定应针对bar检查哪个列,则Laravel将id作为默认值。要覆盖它,只需将该列作为unique

    的第4个参数传递

答案 1 :(得分:0)

你试过了吗?

// Set Primary to null
protected $primaryKey = null;

// Set increment to false
public $incrementing = false;

http://laravel.com/api/source-class-Illuminate.Database.Eloquent.Model.html#37-42