简体   繁体   English

左连接lowdb

[英]Left join with lowdb

I have two "tables"/arrays, user and order, in my JSON database. 我的JSON数据库中有两个“表”/数组,用户和顺序。 It looks like this : 它看起来像这样:

{
  "user": [
    {
      "id": "1",
      "name": "test"
    },
    {
      "id": "2",
      "name": "test"
    },
    {
      "id": "3",
      "name": "test"
    }
  ],
  "order": [
    {
      "user_id": "1",
      "date_order": "2018-01-01",
      "end_order": "2018-01-05"
    },
    {
      "user_id": "2",
      "date_order": "2018-02-01",
      "end_order": "2018-02-05"
    }
  ]
}

I want to retrieve all the users who haven't an order associated to them. 我想要检索没有与之关联的订单的所有用户。 So in this case, only the user #3. 所以在这种情况下,只有用户#3。 Is there a specific function to do a left join ? 是否有特定的功能来进行左连接? I read the README but I can't figure out how to "join" two "tables". 我阅读了README,但我无法弄清楚如何“加入”两个“表”。 Thanks ! 谢谢 !

You can use filter() on user array and use find() on order array to check if there is any object with user_id equal to id of obj in user array. 您可以在用户数组上使用filter()并在order数组上使用find()来检查user_id是否有任何对象在用户数组中等于id的obj。

 const obj = { "user": [ { "id": "1", "name": "test" }, { "id": "2", "name": "test" }, { "id": "3", "name": "test" } ], "order": [ { "user_id": "1", "date_order": "2018-01-01", "end_order": "2018-01-05" }, { "user_id": "2", "date_order": "2018-02-01", "end_order": "2018-02-05" } ] } const res = obj.user.filter(x => !obj.order.find(a => a.user_id === x.id)); console.log(res); 

lowdb does not have a join functionality at this moment. lowdb目前没有join功能。 user and order are treated as databases rather than tables . userorder被视为databases而不是tables

You may create your orders inside your user db if you would like to make queries with lowdb syntax. 如果要使用lowdb语法进行查询,可以在user db创建订单。

In the case you continue using the data structure of your question, you could do something like this: 在您继续使用问题的数据结构的情况下,您可以执行以下操作:

const userIds = db('order').map('user_id');
const users = db('user').filter(user => !userIds.includes(user.id));

Note that in this case, you would be querying all your userIds first. 请注意,在这种情况下,您将首先查询所有userIds This could lead to a performance issue if that number is big. 如果该数字很大,这可能会导致性能问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM