WatermelonDB icon indicating copy to clipboard operation
WatermelonDB copied to clipboard

Relation typo error for returning array in models

Open imatheus-lucas opened this issue 2 years ago • 1 comments

I was creating a project and I came across a typing problem inside watermellowDB follow the facts

Post.ts

import { Associations } from "@nozbe/watermelondb/Model";
import { children, text } from "@nozbe/watermelondb/decorators";
import Comment from "./comment";

export default class Post extends Model {
  static table = "posts";

  @text("title") title!: string;

  static associations: Associations = {
    comments: { type: "has_many", foreignKey: "post_id" },
  };

  @children("comments") comments!: Relation<Comment>;
}

comment.ts

import { Associations } from "@nozbe/watermelondb/Model";
import { relation, text } from "@nozbe/watermelondb/decorators";
import Post from "./post";

export default class Comment extends Model {
  static table = "comments";

  static associations: Associations = {
    posts: { type: "belongs_to", key: "post_id" },
  };

  @text("body") body!: string;

  @relation("posts", "post_id") post!: Relation<Post>;
}

on my main screen I try to bring the information

    (async () => {
      try {
        const posts = await database.get<Post>("posts").query().fetch();
        posts.forEach(async (post) => {
         // on that line it should return an array of comments instead of just a single comment 
          const comments = await post.comments.fetch(); 
        });
        setPosts(posts);
      } catch (err) {
        console.log(err);
      }
    })();
  }, []);

version: "@nozbe/watermelondb": "^0.26.0",

imatheus-lucas avatar Jul 10 '23 15:07 imatheus-lucas

@imatheus-lucas @children must be typed with generic Query type. In your case, Query<Comment>.

erickriva avatar Oct 21 '23 00:10 erickriva