如何在西瓜数据库中获取相关记录?

时间:2019-07-05 09:20:06

标签: database react-native react-native-android watermelondb

我想在react-native中从表中获取相关记录。我正在关注西瓜数据库的官方文件。

 import Blog from "./model/Blog";
 import Post from "./model/Post";
 ...
 export default class App extends Component {
 constructor(props){
 }

 generate = async () => {
 const blogsCollection = database.collections.get("blogs");
 const postsCollection = database.collections.get("posts");
 await database.action(async () => {
   const newBlogs = await blogsCollection.create(blog => {
     blog.name = "Anandtech";
   });
  });
  await database.action(async () => {
  const newPosts = await postsCollection.create(post => {
    post.title = "TSB boss to step down after IT fiasco (bbc.com)";
    post.subtitle = `ID: ${post.id}`;
    post.body =
      "Lorem ipsum sociis natoque penatibus et ultrices volutpat.";
    post.blog.set(newBlogs);
  });
  const blog = await Post.blog.fetch();
  console.log("blogblogblog", blog);
});
}

我一直在关注他们的Relation部分。我不明白这里出了什么问题。下面显示了我的表模式。

    export const mySchema = appSchema({
  version: 2,
  tables: [
    tableSchema({
      name: "blogs",
      columns: [{ name: "name", type: "string" }]
    }),
    tableSchema({
      name: "posts",
      columns: [
        { name: "title", type: "string" },
        { name: "subtitle", type: "string" },
        { name: "body", type: "string" },
        { name: "blog_id", type: "string" }
      ]
    })
  ]
});

这是Post模型类。

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

  static associations = {
    blogs: { type: "belongs_to", key: "blog_id" },
    comments: { type: "has_many", foreignKey: "post_id" }
  };

....

  @relation("blogs", "blog_id")
  blog;
}

0 个答案:

没有答案