花椒 2016-06-13 14:45:54 8135次浏览 1条评论 4 3 0

在多门店的管理中,需要实现的需求是同门店的菜品名称不能重复,
以下为模型部分代码,仅供参考,如有更好方法,请赐教~

public function rules()
{
    return [
        ['name', 'check','on'=>['create']],//定义规则,在create场景中对name进行check方法验证,下面是方法的定义
       ............
    ];
}

public function check($attribute,$params){
    if (empty($this->shop_id)) {
        return $this->addError($attribute,'请选择门店!');
    }
    $dish=Dishes::findOne(['name'=>$this->name,'shop_id'=>$this->shop_id]);
    if($dish){
        $this->addError($attribute, '该菜品名称已存在!');
    }else{
        $this->clearErrors($attribute);
    }
}
觉得很赞
  • 评论于 2016-07-27 00:04 举报

    我也发一个,用yii\validators\UniqueValidator 类实现

    public function rules()
    {
        return [
            ['name', 'required', 'message' => '请选择门店!'],
            ['shop_id', 'required', 'message' => '请输入菜品名称!'],
            ['name', //只有 name 能接收错误提示,数组['name','shop_id']的场合,都接收错误提示
             'unique', 'targetAttribute'=>['name','shop_id'] ,
             'targetClass' => '\models\Dishes', // 模型,缺省时默认当前模型。
             'comboNotUnique' => '选择的门店内,该菜品名称已经存在!' //错误信息
            ],
        ];
    }
    
    1 条回复
    评论于 2018-01-16 14:59 回复

    这样存在一个问题,更新操作时检查这两个字段,发现已经存在了。

    , , , , 觉得很赞
您需要登录后才可以评论。登录 | 立即注册