2017-06-06 55 views
0

我有一個名爲menusoffered的表,其中我基於restaurantid存儲menuname,這是一個外鍵。基於foriegn密鑰的模型中的唯一字段驗證yii2

在我的menusoffered模型中,我聲明menuname有一個唯一的驗證器,但是這是檢查整個表的唯一性。

我想要它檢查基於restaurantid, 唯一性可以任何人可以幫助我如何使menuname獨特的特定restaurantid

下面是我給定的菜單模式,

class Menusoffered extends \yii\db\ActiveRecord 
{ 

/** 
* @inheritdoc 
*/ 
public static function tableName() 
{ 
    return 'menusoffered'; 
} 

/** 
* @inheritdoc 
*/ 
public function rules() 
{ 
    return [ 
      ['phase_id', 'required', 'message' => 'Please select Phase'], 
      ['menuname', 'required'],   
      ['price', 'required'], 
      [['price'],'integer' , 'message' =>'Price should be in digits'], 
      [['image_url'], 'file'], 
      [['description', 'status'], 'string'], 
      [['createdts','restaurantid'], 'safe'], 
      ['master_menu_sepcality_id', 'required', 'message' => 'Please select Speciality'], 
      ['master_menu_type_id', 'required', 'message' => 'Please select Type'], 
      ['menuname', 'unique', 'with'=>'restaurantid'], 
      [['restaurantid'], 'exist', 'skipOnError' => true, 'targetClass' => Restaurant::className(), 'targetAttribute' => ['restaurantid' => 'id']], 
    ]; 
} 

/** 
* @inheritdoc 
*/ 
public function attributeLabels() 
{ 
    return [ 
     'id' => 'ID', 
     'master_menu_sepcality_id' => 'Master Menu Sepcality ID', 
     'master_menu_type_id' => 'Master Menu Type ID', 
     'item' => 'Item', 
     'price' => 'Price', 
     'restaurantid' => 'Restaurantid', 
     'phase_id' => 'Phase ID', 
     'description' => 'Description', 
     'image_url' => 'Image Url', 
     'status' => 'Status', 
     'createdts' => 'Createdts', 
    ]; 
} } 

回答

0

試試這個:Yii2 Unique Validator

// a1 and a2 need to be unique together, only a1 will receive error message 
['a1', 'unique', 'targetAttribute' => ['a1', 'a2']] 
+0

感謝朋友,它的工作對我來說唯一的事情是在我的活性形式,沒有restaurantid字段,以便我在那裏添加了隱藏字段非常感謝你 –