Recod relation with skygear


#1
const Note = skygear.Record.extend('post');
skygear.publicDB.save(new Note({
  'title': 'post title',
  'content':'post content'
  })).then((record) => {

  });
const Comment = skygear.Record.extend('comment');
skygear.publicDB.save(new Comment({
  'comment': 'comment'
  })).then((record) => {

  });

how can i make a relation with this two recod’s ? Thanks


#2

@arsene You may check out the Record Relation guide: https://docs.skygear.io/guides/cloud-db/data-types/js/#record-relations

You can use a skygear.Reference (or even an array of skygear.Reference if it helps!) to store relation.

const Note = skygear.Record.extend('post');
var note1 = new Note({
  'title': 'post title',
  'content':'post content'
  });
skygear.publicDB.save(note1).then((record) => {});

const Comment = skygear.Record.extend('comment');
skygear.publicDB.save(new Comment({
  'comment': 'comment',
  'note': new skygear.Reference(note1)
  })).then((record) => {

  });

#3

in fact my question is this one, a relationship on two record. like a post and a comment, from which I can comment on a post directly. like on a blog for example


#4

yea, in the above example, the comment will have a relation with note1


#5

error {"_id":“comment/d654303c-b5f5-427f-9cea-3c406e3aa781”,"_type":“error”,“code”:10000,“message”:“pq: insert or update on table “comment” violates foreign key constraint “fk_note_pathologie__id””,“name”:“UnexpectedError”}


#6

I have a table e.g: Post, as each post has its identifier. I will love to comment by post equal to its identifier


#7

Please put the save of commend after the save of note1 resolved as follow:

const Note = skygear.Record.extend('post');
var note1 = new Note({
  'title': 'post title',
  'content':'post content'
});

skygear.publicDB.save(note1).then((savedNote) => {
  const Comment = skygear.Record.extend('comment');
  skygear.publicDB.save(new Comment({
    'comment': 'comment',
    'note': new skygear.Reference(note1)
  })).then((savedComment) => {
    console.log(savedComment);
  });
});

The original code base is executing both save in parallel, so the comment may arrive server before the note. IN that case, an FK error will raise.


#8

this creates a new post with the same content


#9

the commentary is saved separately with the post


#10

If you want to associate the comment to the same note. You should provide the target id in the note object.

const Note = skygear.Record.extend('post');
var note1 = new Note({
  'id': 'note/thetargetnoteid', // You need to query it and remember it somewhere.
  'title': 'post title',
  'content':'post content'
});

skygear.publicDB.save(note1).then((savedNote) => {
  const Comment = skygear.Record.extend('comment');
  skygear.publicDB.save(new Comment({
    'comment': 'comment',
    'note': new skygear.Reference(note1)
  })).then((savedComment) => {
    console.log(savedComment);
  });
});

#11

thank you @rickmak, but I already find the answer