cube.js join 的处理

时间:2021-01-27 13:56:50   收藏:0   阅读:0

支持join 模式

joins: {
  TargetCubeName: {
    relationship: `belongsTo` || `hasMany` || `hasOne`,
    sql: `SQL ON clause`
  }
}
 
{
  member: "Posts.authorName",
  operator: "set"
}

参数说明

注意定义join 的relationship必须明确,不然可能会产生不一样的结果

 
cube("Users", {
  joins: {
    Profile: {
      relationship: `hasOne`,
      sql: `${Users}.id = ${Profile}.user_id`
    }
  }
});

hasMany
定义一对多的场景,比如一个作者有多本书

 
cube("Authors", {
  joins: {
    Books: {
      relationship: `hasMany`,
      sql: `${Authors}.id = ${Books}.author_id`
    }
  }
});

belongsTo
定义多对一的场景,比如一个客户有多个订单,对于order 与客户的关联就是订单属于客户

 
cube("Orders", {
  joins: {
    Customers: {
      relationship: `belongsTo`,
      sql: `${Orders}.customer_id = ${Customers}.id`
    }
  }
});
 
sql: `${Orders}.customer_id = ${Customers}.id`

设置主键

为了join 的正确处理,很多时候设置正确的主键也很必要,注意主键是在维度定义的

dimensions: {
  authorId: {
    sql: `id`,
    type: `number`,
    primaryKey: true
  }
}

cube 的引用

使用${CUBE} 可以引用当前的cube schema 定义,在处理join 的时候很有必要

dimensions: {
  name: {
    sql: `${CUBE}.name`,
    type: `string`
  }
}

传递join

cube.js 基于Dijkstra‘s algorithm 算法可以解决a-b,b-c 然后a-c 的关联问题
比如:

 
cube(`A`, {
  // ...
  joins: {
    B: {
      sql: `${A}.b_id = ${B}.id`,
      relationship: `belongsTo`
    }
  },
?
  measures: {
    count: {
      type: `count`
    }
  }
});
?
cube(`B`, {
  // ...
  joins: {
    C: {
      sql: `${B}.c_id = ${C}.id`,
      relationship: `belongsTo`
    }
  }
});
?
cube(`C`, {
  // ...
?
  dimensions: {
    category: {
      sql: `category`,
      type: `string`
    }
  }
}); 

我们可以使用

{
  measures: [‘A.count‘],
  dimensions: [‘C.category‘]
}

参考资料

https://cube.dev/docs/joins
https://cube.dev/docs/direction-of-joins/

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!