LoginSignup
1
1

More than 3 years have passed since last update.

dieselでAssociations

Posted at

概要

タイトルのことをやりたかったので以下を参考にやってみました
https://docs.diesel.rs/diesel/associations/index.html

一つのRoomに複数のCommentが存在しているケースでやってみます。

モデル

dieselでは現状has_manyの概念がなく、belongs_toを使って関連付けをするようです。

Room

親となるRoomの定義です。
Identifiableのアトリビュートが必要なようです。

#[derive(Identifiable, Queryable, PartialEq, Debug)]
#[table_name="rooms"]
pub struct Room {
    pub id: i32,
    pub name: String,
}

Comment

次に子となるCommentの定義です。親と同じくIdentifiableが必要です。

また、子にはAssociationsのアトリビュートも付ける必要があります。
さらにbelongs_toで親のモデルを指定しましょう。

#[derive(Identifiable, Queryable, Associations, PartialEq, Debug)]
#[belongs_to(Room)]
#[table_name="comments"]
pub struct Comment {
    pub id: i32,
    pub message: String,
    pub room_id: i32,
}

呼び出し部分

この例ではRoomのidが1のデータを取得し、それに紐づくCommentを全て取得しています。

let room = rooms.find(1).first::<Room>(&connection)?;
let comments = Comment::belonging_to(&room)
    .load::<Comment>(&connection)
    .expect("error on load comments");

補足

foreign_keyを指定する

デフォルトはbelongs_toで指定したモデルを元に"{モデル名(snake case)}_id"でforeign_keyを判別するようです。

例えばモデル名をRoomModelとCommentModelに変更すると、room_model_idをforeign_keyとして使おうとして、プロパティが存在しないためエラーとなります。

#[derive(Identifiable, Eq, PartialEq, Debug, Queryable, Associations)]
#[belongs_to(RoomModel)]
#[table_name="comments"]
pub struct CommentModel {
    pub id:i32,
    pub room_id: i32,
    pub message: String,
}

このような場合はbelongs_toにforeign_keyを指定することにより、エラーが解消されます。

#[derive(Identifiable, Eq, PartialEq, Debug, Queryable, Associations)]
#[belongs_to(RoomModel, foreign_key = "room_id")] // foreign_keyを指定
#[table_name="comments"]
pub struct CommentModel {
    pub id:i32,
    pub room_id: i32,
    pub message: String,
}

さいごに

ZEROBILLBANKでは一緒に働く仲間を募集中です。
ZEROBILLBANK JAPAN Inc.

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1