Nozbe / WatermelonDB

🍉 Reactive & asynchronous database for powerful React and React Native apps ⚡️
https://watermelondb.dev
MIT License
10.62k stars 600 forks source link

Relation typo error for returning array in models #1624

Open imatheus-lucas opened 1 year ago

imatheus-lucas commented 1 year ago

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",

erickriva commented 1 year ago

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