diff --git a/migrations/2018-04-23-142746_create_post_authors/down.sql b/migrations/2018-04-23-142746_create_post_authors/down.sql new file mode 100644 index 0000000..129bf59 --- /dev/null +++ b/migrations/2018-04-23-142746_create_post_authors/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +DROP TABLE post_authors; diff --git a/migrations/2018-04-23-142746_create_post_authors/up.sql b/migrations/2018-04-23-142746_create_post_authors/up.sql new file mode 100644 index 0000000..6819c74 --- /dev/null +++ b/migrations/2018-04-23-142746_create_post_authors/up.sql @@ -0,0 +1,6 @@ +-- Your SQL goes here +CREATE TABLE post_authors ( + id SERIAL PRIMARY KEY, + post_id INTEGER REFERENCES posts(id) ON DELETE CASCADE NOT NULL, + author_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL +) diff --git a/src/models/mod.rs b/src/models/mod.rs index 30b33e5..360d247 100644 --- a/src/models/mod.rs +++ b/src/models/mod.rs @@ -1,5 +1,6 @@ pub mod blog_authors; pub mod blogs; pub mod instance; +pub mod post_authors; pub mod post; pub mod user; diff --git a/src/models/post_authors.rs b/src/models/post_authors.rs new file mode 100644 index 0000000..f91592e --- /dev/null +++ b/src/models/post_authors.rs @@ -0,0 +1,34 @@ +use diesel; +use diesel::{PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods}; +use schema::post_authors; + +#[derive(Queryable, Identifiable)] +pub struct PostAuthor { + pub id: i32, + pub post_id: i32, + pub author_id: i32 +} + +#[derive(Insertable)] +#[table_name = "post_authors"] +pub struct NewPostAuthor { + pub post_id: i32, + pub author_id: i32 +} + +impl PostAuthor { + pub fn insert (conn: &PgConnection, new: NewPostAuthor) -> PostAuthor { + diesel::insert_into(post_authors::table) + .values(new) + .get_result(conn) + .expect("Error saving new blog author") + } + + pub fn get(conn: &PgConnection, id: i32) -> Option { + post_authors::table.filter(post_authors::id.eq(id)) + .limit(1) + .load::(conn) + .expect("Error loading blog author by id") + .into_iter().nth(0) + } +} diff --git a/src/schema.rs b/src/schema.rs index 46f91ec..182e745 100644 --- a/src/schema.rs +++ b/src/schema.rs @@ -30,6 +30,14 @@ table! { } } +table! { + post_authors (id) { + id -> Int4, + post_id -> Int4, + author_id -> Int4, + } +} + table! { posts (id) { id -> Int4, @@ -60,6 +68,8 @@ table! { joinable!(blog_authors -> blogs (blog_id)); joinable!(blog_authors -> users (author_id)); joinable!(blogs -> instances (instance_id)); +joinable!(post_authors -> posts (post_id)); +joinable!(post_authors -> users (author_id)); joinable!(posts -> blogs (blog_id)); joinable!(users -> instances (instance_id)); @@ -67,6 +77,7 @@ allow_tables_to_appear_in_same_query!( blog_authors, blogs, instances, + post_authors, posts, users, );