I have a table called menusoffered
where I am storing menuname
based on restaurantid
which is a foreign key.
In my menusoffered
model I have declared that menuname
has a unique validator, but this is checking the uniqueness from the entire table.
I want it to check uniqueness based on restaurantid
, Can any one help me how to make this menuname
unique for particular restaurantid
?
Below is my given menu model,
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',
];
} }
Try this: Yii2 Unique Validator :
// a1 and a2 need to be unique together, only a1 will receive error message
['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.