重新思考数据库合并结果

时间:2018-02-21 11:19:07

标签: rethinkdb

我是RethinkDB的新手。加入后如何将正确的结果作为公司输入左表:[{right},...] 现在我使用这个查询 r.db('Auth').table('Users').filter({'email': '******'}).eqJoin('id', r.db('CloudCRM').table("Emploees"),{index: 'user_id'}).zip().without('user_id').eqJoin("company_id", r.db('Auth').table("Companies"), {index: 'id'}) 结果如下:

{
"left": {
"birthdate": ****,
"company_id":  "b191c180-0c51-4317-b545-2597a15d6ddb" ,
"email": ******, »
"firstName":  "****" ,
"id":  "c49c8712-8904-42ae-9819-4ab54b4d56ff" ,
"lastName":  "******" ,
"password":  "******" ,
"phonenumber":  "*****" ,
"role":  "user"
} ,
"right": {
"companyTitle":  "*******“" ,
"director":  "b2020c9e-4d01-41d8-82fa-c080bbeb5a68" ,
"domain":  "*******" ,
"id":  "b191c180-0c51-4317-b545-2597a15d6ddb"
}
}

我想得到的是:

{
"birthdate": ******,
"company_id":  "b191c180-0c51-4317-b545-2597a15d6ddb" ,
"email": *******, »
"firstName":  "*****" ,
"id":  "c49c8712-8904-42ae-9819-4ab54b4d56ff" ,
"lastName":  "******" ,
"password":  "******" ,
"phonenumber":  "******" ,
"role":  "user"
"companies": [{
"companyTitle":  "********" ,
"director":  "b2020c9e-4d01-41d8-82fa-c080bbeb5a68" ,
"domain":  "*******" ,
"id":  "b191c180-0c51-4317-b545-2597a15d6ddb"
}]
}

2 个答案:

答案 0 :(得分:0)

这就是我解决这个问题的方法

r.db('Auth').table('Users').filter({'email': 'ignas.rackus@gmail.com'}).eqJoin('id', r.db('CloudCRM').table("Emploees"),{index: 'user_id'}).zip().without('user_id').eqJoin("company_id", r.db('Auth').table("Companies"), {index: 'id'})
  .hasFields('position_id').eqJoin("position_id", r.db('CloudCRM').table("Possitions"), {index: 'id'})
  .map({
  id : r.row('left')('id'),
  firstName : r.row('left')('firstName'),
  lastName : r.row('left')('lastName'),
  email : r.row('left')('email'),
  password : r.row('left')('password'),
  birthdate : r.row('left')('birthdate'),
  phonenumber : r.row('left')('phonenumber'),
  companies : r.row('right')
})

这可能不是最佳解决方案,所以如果有人知道更好,请纠正我

答案 1 :(得分:0)

您可以避免容易出错地按值复制每个属性,只需选择合并left值(公司)的right值(用户)。例如(为简单起见,下面的查询更容易理解),

r.db('test')
  .table('users')
  .eqJoin('company_id', r.table('companies'))
  .map((row) => row('left').merge({ company: row('right') }))
  ;

输出:

{
    "birthdate":  "****" ,
    "company": {
        "companyTitle":  "*******“" ,
        "director":  "b2020c9e-4d01-41d8-82fa-c080bbeb5a68" ,
        "domain":  "*******" ,
        "id":  "b191c180-0c51-4317-b545-2597a15d6ddb"
    } ,
    "company_id":  "b191c180-0c51-4317-b545-2597a15d6ddb" ,
    "email":  "******" ,
    "firstName":  "****" ,
    "id":  "c49c8712-8904-42ae-9819-4ab54b4d56ff" ,
    "lastName":  "******" ,
    "password":  "******" ,
    "phonenumber":  "*****" ,
    "role":  "user"
}

请注意,结果会提供company字段,因为您的用户表每个用户只有一个company_id