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
版权声明:本文标题:php - Codeigniter 4 - how to properly use entities - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736311803a1934870.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论