RethinkDB以关系插入数据

时间:2015-04-27 22:37:31

标签: rethinkdb rethinkdb-python

我有一张桌子A和一张桌子。

表B与A的关系为a_id

我已在表A中创建了该文档。 我想知道如何使用表B中带有外键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)

1 个答案:

答案 0 :(得分:2)

你走在正确的轨道上,但ReQL与SQL的逻辑不同,它通常更像是一个流程。因此,您的查询需要从数据源开始,以便它可以流入插入部分。所以这是我认为你想要的版本(Python格式):

var one_day = 86400000; // (24 * 60 * 60 * 1000) no sense in computing a static value

initializeFairEvents = function(fair) {
  // Assuming fair is a model instance
  var fairLengthDays = fair.num_days;
  var eventStart = Date.parse(fair.start_date);
  var eventEnd = Date.parse(fair.end_date);
  var events = fair.events;
  var dailyEventLength = eventEnd - eventStart - one_day * (fairLengthDays - 1);

  // It looks like you only want to add events if there are no events currently
  if (events === null || events.length === 0) {
    for (var i = 0; i < fairLengthDays; i++) {
      var newEvent = fair.events.create({
        name: (fairLengthDays === 1) ?
          fair.name :
          (fair.name + ' - day ' + (i + 1)), 
        start_date: (i * one_day) + eventStart,
        end_date: (i * one_day) + eventStart + dailyEventLength,
        preserve: true
      });

      // newEvent.id 

      fair.events.push(newEvent);
    }
  }
};