首页 > 解决方案 > 未找到列:1054 'where 子句'中的未知列 'id'(SQL:从 `item` 中选择 count(*) 作为聚合,其中 `barcode` = A002 和 `id` <> 12)

问题描述

我尝试更新我的表Item,但我在我的控制器中使用了唯一验证,我在我的模型中设置了主键 = 'item_id' 但是我一直收到这个错误说未知的列 id,即使我已经将主键设置为我的 item_id模型,当我尝试使用验证时:

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

此错误不会出现并且程序可以工作,但是在唯一的条形码中,它正在检查自己的唯一列并且它失败但看到了自己的字段。这就是为什么我将验证更改为:

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

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

找不到列:1054 'where 子句'中的未知列 'id'(SQL:从itemwhere barcode= A002 和id<> 12 中选择 count(*) 作为聚合)

项目控制器:

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

标签: laravelvalidationunique

解决方案


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

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

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


推荐阅读