Add relation between posts and authors
This commit is contained in:
parent
e506cd21b7
commit
a816bb00b7
@ -0,0 +1,2 @@
|
||||
-- This file should undo anything in `up.sql`
|
||||
DROP TABLE post_authors;
|
6
migrations/2018-04-23-142746_create_post_authors/up.sql
Normal file
6
migrations/2018-04-23-142746_create_post_authors/up.sql
Normal 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
|
||||
)
|
@ -1,5 +1,6 @@
|
||||
pub mod blog_authors;
|
||||
pub mod blogs;
|
||||
pub mod instance;
|
||||
pub mod post_authors;
|
||||
pub mod post;
|
||||
pub mod user;
|
||||
|
34
src/models/post_authors.rs
Normal file
34
src/models/post_authors.rs
Normal 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)
|
||||
}
|
||||
}
|
@ -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,
|
||||
);
|
||||
|
Loading…
Reference in New Issue
Block a user