简单喜欢
Create table like(
user_id int,
post_id int,
Constraint pk_like primary key (user_id, post_id),
Constraint fk_user foreign key (user_id) references UserTable(id),
Constraint fk_post foreign key (post_id) references PostTable(id)
);
如果用户喜欢你添加一行,
Insert into like values (@userId,@postId);
如果他不喜欢他的喜欢你删除
Delete from like where user_id = @userId and post_id = @post_id;
如果您的应用中存在“不喜欢”,则应添加布尔列 1 表示喜欢,0 表示不喜欢,如果您有更多喜欢和不喜欢的内容,例如:hate、love、ungry。强>
#Call in query to like(1), unlike(2), hate(3)
call sp_Like(@userID,@postId,1);
#To dont like,unlike,hate,etc anymore you send (-1) in likeType.
call sp_Like(@userID,@postId,-1);
#This is your query
call sp_Like(@userID,@postId,likeType);
Create table yourDB.like(
user_id int,
post_id int,
likeType int,
Constraint pk_like primary key (user_id, post_id),
Constraint fk_user foreign key (user_id) references UserTable(id),
Constraint fk_post foreign key (post_id) references PostTable(id)
);
DELIMITER $$
USE yourDB$
DROP PROCEDURE IF EXISTS yourDB.sp_Like$$
CREATE PROCEDURE yourDB.sp_Like
(
IN ruser_id int,
IN rpost_id int,
IN rlikeType int
)
BEGIN
DECLARE exit handler for sqlexception
BEGIN
ROLLBACK;
SHOW ERRORS LIMIT 1;
select "-1" as "response";
END;
START TRANSACTION;
#check if he done like before
If exists(select post_id from like where user_id = ruser_id and post_id = rpost_id)
Then
#if user doesnt like or unlike, love, hate, anymore
If rlikeType = -1 then delete from like where
user_id = ruser_id and post_id = rpost_id;
else
#if user change like type
Update like set likeType = rlikeType where user_id = ruser_id and post_id = rpost_id;
end if;
Else
#if he doesnt like yet
Insert into like values (ruser_id,rpost_id,rlikeType);
End if;
select "1" as "response";
COMMIT;
END$$
DELIMITER ;