Add a model for likes

This commit is contained in:
Bat 2018-05-10 16:54:35 +01:00
parent b81b9f90ec
commit 7b5f0f1704
5 changed files with 51 additions and 0 deletions

View File

@ -0,0 +1,2 @@
-- This file should undo anything in `up.sql`
DROP TABLE likes;

View File

@ -0,0 +1,7 @@
-- Your SQL goes here
CREATE TABLE likes (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL,
post_id INTEGER REFERENCES posts(id) ON DELETE CASCADE NOT NULL,
creation_date TIMESTAMP NOT NULL DEFAULT now()
)

29
src/models/likes.rs Normal file
View File

@ -0,0 +1,29 @@
use chrono;
use diesel::{PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods};
use schema::likes;
#[derive(Queryable)]
pub struct Like {
id: i32,
user_id: i32,
post_id: i32,
creation_date: chrono::NaiveDateTime
}
#[derive(Insertable)]
#[table_name = "likes"]
pub struct NewLike {
user_id: i32,
post_id: i32
}
impl Like {
pub fn get(conn: &PgConnection, id: i32) -> Option<Like> {
likes::table.filter(likes::id.eq(id))
.limit(1)
.load::<Like>(conn)
.expect("Error loading like by ID")
.into_iter().nth(0)
}
}

View File

@ -3,6 +3,7 @@ pub mod blogs;
pub mod comments; pub mod comments;
pub mod follows; pub mod follows;
pub mod instance; pub mod instance;
pub mod likes;
pub mod post_authors; pub mod post_authors;
pub mod posts; pub mod posts;
pub mod users; pub mod users;

View File

@ -56,6 +56,15 @@ table! {
} }
} }
table! {
likes (id) {
id -> Int4,
user_id -> Int4,
post_id -> Int4,
creation_date -> Timestamp,
}
}
table! { table! {
post_authors (id) { post_authors (id) {
id -> Int4, id -> Int4,
@ -102,6 +111,8 @@ joinable!(blog_authors -> users (author_id));
joinable!(blogs -> instances (instance_id)); joinable!(blogs -> instances (instance_id));
joinable!(comments -> posts (post_id)); joinable!(comments -> posts (post_id));
joinable!(comments -> users (author_id)); joinable!(comments -> users (author_id));
joinable!(likes -> posts (post_id));
joinable!(likes -> users (user_id));
joinable!(post_authors -> posts (post_id)); joinable!(post_authors -> posts (post_id));
joinable!(post_authors -> users (author_id)); joinable!(post_authors -> users (author_id));
joinable!(posts -> blogs (blog_id)); joinable!(posts -> blogs (blog_id));
@ -113,6 +124,7 @@ allow_tables_to_appear_in_same_query!(
comments, comments,
follows, follows,
instances, instances,
likes,
post_authors, post_authors,
posts, posts,
users, users,