未找到列:'where clause' 中的 1054 未知列 'id'(SQL:select 计数(*)作为来自 `item` 的聚合,其中 `barcode` = A002 和 `id` <> 12)

Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select count(*) as aggregate from `item` where `barcode` = A002 and `id` <> 12)

我尝试更新我的 table Item 但我在我的控制器中使用了唯一验证,我在我的模型中设置了主键 = 'item_id' 但我一直收到此错误即使我在我的模型中将主键设置为 item_id,当我尝试使用验证时,也会说未知的列 ID :

 // 'barcode' => 'unique:item' // 

这个错误没有出现,程序可以运行,但在条码的唯一性中,它正在检查自己的唯一列,但它失败了,但看到了自己的字段。这就是为什么我将验证更改为:

// 'barcode' => 'unique:item,barcode,'.$item_id, // 

当我尝试更新时出现此错误:

Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select count(*) as aggregate from item where barcode = A002 and id <> 12)

物品控制器:

public function update(Request $request,$item_id)
    {
        $messages = [
            'unique' => 'Sorry this barcode already exist....',
        ];
        $this->validate($request,[
           'barcode' => 'unique:item,barcode,'.$item_id,
        ],$messages);
        $data = $request->except(['_token']);
        Item::where('item_id',$item_id)->update($data);
        return redirect('/item')->with('sukses','item successfully updated');
    }

这是我的模型 Item.php :

class Item extends Model
{
    protected $table = 'item';
    protected $primaryKey = 'item_id';
    protected $fillable = ['barcode','item_name','category_id','satuan_id','price'];

    public function category_r(){
        return $this->belongsTo('App\Category','category_id','category_id');
    }
    public function satuan_r(){
        return $this->belongsTo('App\Satuan','satuan_id','satuan_id');
    }
}

当您使用自定义主键时,您还应该将其名称添加到验证中:

$this->validate($request,[
           'barcode' => 'unique:item,barcode,'.$item_id.',item_id'
        ],$messages);

https://laravel.com/docs/5.2/validation#rule-unique