2

I have a table A and a table B.

Table B has a relationship with A with the key a_id.

I already created the document in a in table A. I'm wondering how to insert data in a single query using a doc in table B with foreign key A.

r.db('DB').table('B').insert([{
    'b_data': ...,
    'a_id': r.db('DB').table('a').filter(r.row['name'] == 'some_name')
} for p in a]).run(conn)
Alexis Benoist
  • 2,400
  • 2
  • 17
  • 23

1 Answers1

2

You are on the right track, but ReQL differs from the logic of SQL in that it is usually more like a flow. So your query needs to start with the source of the data so it can flow into the insert portion. So here is a version of what I think you want (in Python format):

r.db('DB').table('a').filter({'name':'some_name}).for_each(
    r.db('DB').table('b').insert(
        {'name':r.row['name'],'b_data':'something'}
    )
).run(conn)
larkost
  • 89
  • 3
  • I’ve got ReDB tables with a one-to-many relationship, would I need to check for referential integrity this way every time? – Qasim Dec 02 '18 at 06:32
  • I don't really understand your question. RethinkDB did/does not provide any referential integrity between tables. There are/were limited joins on queries, but nothing on inserts. If you mean within a single document/object, then you have lost me. – larkost Dec 04 '18 at 00:33
  • Not within a single document/object - I was looking at a one-to-many relationship where the _one_ element might get removed, leaving _many_ elements to still exist. As you said, ReDB doesn't provide referential integrity, so I guess I'll have to manually check for this stuff... – Qasim Dec 05 '18 at 15:45