I haven’t used entities much and I am not sure if I am using correctly. I am trying to add favorite resorts to a table. Here is my code:
function myFavorite() {
$resortID = $this->request->getVar('resortID');
$user_id = $this->current_user->id;
if ($resortID && $user_id) {
// Load the model
$SknowedWeatherFavoritesModel = new AppModelsSknowedWeatherFavoritesModel();
// Create a new entity
$SknowedWeatherFavoritesEntity = new AppEntitiesSknowedWeatherFavoritesEntity();
$SknowedWeatherFavoritesEntity->sknowedWeather_id = $resortID;
$SknowedWeatherFavoritesEntity->user_id = $user_id;
// Save the entity
if ($SknowedWeatherFavoritesModel->save($SknowedWeatherFavoritesEntity)) {
return "Favorite added successfully.";
die();
} else {
return "Failed to add favorite.";
die();
}
} else {
return "Missing resortID or user_id.";
die();
}
}
The above works. It I click myFavorite button on a resort, it will add, say for exmaple, id (auto inc), resortID and user_id.
the problem I am facing it that if I hit the myFavorite button again, it adds another identical record except the auto inc is increase by 1. I was reading the ->save will insert if new and update if already existing. How would I ensure no duplicate entry? or am I doing this all wrong?
Thank you for any pointers.