admin管理员组

文章数量:1122832

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 \App\Models\SknowedWeatherFavoritesModel();

        // Create a new entity
        $SknowedWeatherFavoritesEntity = new \App\Entities\SknowedWeatherFavoritesEntity();
        $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?

This is my db (unrelated fields removed);

CREATE TABLE `sknowedWeatherFavorites` (
  `sknowedWeatherFavorites_id` int NOT NULL,
  `sknowedWeather_id` varchar(17) CHARACTER SET utf8mb3 COLLATE 
utf8mb3_general_ci NOT NULL,
  `user_id` int UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE `sknowedWeather` (
  `id` varchar(17) NOT NULL,
  `website` varchar(64) DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;

CREATE TABLE `user` (
  `id` int UNSIGNED NOT NULL,
  `name` varchar(128) NOT NULL,
  `updated_at` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;

Relationships as follows;

Thank you for any pointers.

本文标签: phpCodeigniter 4how to properly use entitiesStack Overflow