Add relation between posts and authors

This commit is contained in:
Bat 2018-04-23 15:37:49 +01:00
parent e506cd21b7
commit a816bb00b7
5 changed files with 54 additions and 0 deletions

View File

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

View File

@ -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
)

View File

@ -1,5 +1,6 @@
pub mod blog_authors; pub mod blog_authors;
pub mod blogs; pub mod blogs;
pub mod instance; pub mod instance;
pub mod post_authors;
pub mod post; pub mod post;
pub mod user; pub mod user;

View File

@ -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<PostAuthor> {
post_authors::table.filter(post_authors::id.eq(id))
.limit(1)
.load::<PostAuthor>(conn)
.expect("Error loading blog author by id")
.into_iter().nth(0)
}
}

View File

@ -30,6 +30,14 @@ table! {
} }
} }
table! {
post_authors (id) {
id -> Int4,
post_id -> Int4,
author_id -> Int4,
}
}
table! { table! {
posts (id) { posts (id) {
id -> Int4, id -> Int4,
@ -60,6 +68,8 @@ table! {
joinable!(blog_authors -> blogs (blog_id)); joinable!(blog_authors -> blogs (blog_id));
joinable!(blog_authors -> users (author_id)); joinable!(blog_authors -> users (author_id));
joinable!(blogs -> instances (instance_id)); joinable!(blogs -> instances (instance_id));
joinable!(post_authors -> posts (post_id));
joinable!(post_authors -> users (author_id));
joinable!(posts -> blogs (blog_id)); joinable!(posts -> blogs (blog_id));
joinable!(users -> instances (instance_id)); joinable!(users -> instances (instance_id));
@ -67,6 +77,7 @@ allow_tables_to_appear_in_same_query!(
blog_authors, blog_authors,
blogs, blogs,
instances, instances,
post_authors,
posts, posts,
users, users,
); );