【问题标题】:How to join table one to many using objection js如何使用反对js加入一对多表
【发布时间】:2020-09-03 15:55:08
【问题描述】:

我只是使用了 knex 反对 js。目前我有一个一对多的表关系如下。

表用户组:

   Column   |           Type           | Collation | Nullable |                  Default                   | Storage  | Stats target | Description 
------------+--------------------------+-----------+----------+--------------------------------------------+----------+--------------+-------------
 id         | integer                  |           | not null | nextval('dl_user_groups_id_seq'::regclass) | plain    |              | 
 title      | character varying(128)   |           | not null |                                            | extended |              | 
 slug       | character varying(128)   |           | not null |                                            | extended |              | 
 desc       | character varying(512)   |           |          |                                            | extended |              | 
 created_at | timestamp with time zone |           | not null | CURRENT_TIMESTAMP                          | plain    |              | 
 updated_at | timestamp with time zone |           | not null | CURRENT_TIMESTAMP                          | plain    |              | 

表角色:

    Column     |           Type           | Collation | Nullable |               Default                | Storage  | Stats target | Description 
---------------+--------------------------+-----------+----------+--------------------------------------+----------+--------------+-------------
 id            | integer                  |           | not null | nextval('dl_roles_id_seq'::regclass) | plain    |              | 
 user_group_id | integer                  |           | not null |                                      | plain    |              | 
 title         | character varying(128)   |           | not null |                                      | extended |              | 
 slug          | character varying(128)   |           | not null |                                      | extended |              | 
 desc          | character varying(512)   |           |          |                                      | extended |              | 
 created_at    | timestamp with time zone |           | not null | CURRENT_TIMESTAMP                    | plain    |              | 
 updated_at    | timestamp with time zone |           | not null | CURRENT_TIMESTAMP                    | plain    |              | 

这可以模拟roles.js:

'use strict';

const { Model } = require('objection');
const UserGroupsModel = require(__basedir + '/app/models/user_groups');


class RolesModel extends Model {
    static get tableName() {
        return 'dl_roles';
    }

    static get jsonSchema() {
        return {
            type: 'object',
            required: ['user_group_id', 'title'],
            properties: {
                id: { type: 'integer' },
                user_group_id: { type: 'integer' },
                title: { type: 'string', minLength: 1, maxLength: 128 },
                slug: { type: 'string', minLength: 1, maxLength: 128 },
                desc: { type: 'string', maxLenght: 512 }
            }
        }
    }

    static get relationMappings() {
        return {
            user_groups: {
                relation: Model.BelongsToOneRelation, 
                modelClass: UserGroupsModel, 
                join: {
                    from: 'dl_roles.user_group_id',
                    to: 'dl_user_groups.id'
                }
            }
        };
    };
}

module.exports = RolesModel;

user_groups.js

'use strict';

const { Model } = require('objection');
const Crypto = require('crypto');
const RolesModel = require(__basedir + '/app/models/roles');


class UserGroupsModel extends Model {
    static get tableName() {
        return 'dl_user_groups';
    }

    static get jsonSchema() {
        return {
            type: 'object',
            required: ['title'],
            properties: {
                id: { type: 'integer' },
                title: { type: 'string', minLength: 1, maxLength: 128 },
                slug: { type: 'string', minLength: 1, maxLength: 128 },
                desc: { type: 'string', maxLength: 512 }
            }
        }
    }

    static get relationMappings() {
        return {
            roles: {
                relation: Model.HasManyRelation, 
                modelClass: RolesModel,
                join: {
                    from: 'dl_user_groups.id',
                    to: 'dl_roles.user_group_id'
                }
            }
        };
    };
}

module.exports = UserGroupsModel;

这是我要转换为反对 js 的查询。

select ug.title as group, r.title as role, r.slug, r.desc 
from public.dl_roles r 
join public.dl_user_groups ug on r.user_group_id = ug.id;

结果:

 group  |     role      |     slug      | desc 
--------+---------------+---------------+------
 TELKM  | Administrator | administrator | 
 TELKM  | Instructor    | instructor    | 
 TELKM  | Learner       | learner       | 
 TELKM  | Guest         | guest         | 
 APPS   | Apps          | Apps          | 

这是我的反对意见:

'use strict';

const RolesModel = require(__basedir + '/app/models/roles');
const Slugify = require('slugify');


exports.getRolesAll = async function() {
    return new Promise(async (resolve, reject) => {
        try {
            let _data = await RolesModel
            .query()
            .joinRelated('user_groups');
            return resolve({
                statusCode: 200,
                data: _data,
                message: 'All data'
            });
        } catch (err) {
            return reject(err);
        }
    });
};

我尝试过使用joinRelated 和eager 但不起作用。我希望高级可以给我答案如何加入一对多并从父表中获取所有字段,就像我上面的查询一样。

谢谢。

【问题讨论】:

  • 我建议您首先尝试进行更简单的测试,以了解这些关系映射和急切查询是如何工作的。因此,只需声明几个模型并进行查询并删除其他所有内容。您也很难弄清楚如何调试具有如此多潜在位置的代码导致问题。当您首先使小块单独工作时,您可以开始尝试将它们组合起来以完成解决方案。 stackoverflow.com/help/minimal-reproducible-example

标签: knex.js objection.js


【解决方案1】:

我已经通过使用原始查询解决了我的问题。这是我的查询使用反对js。

RolesModel
.query()
.select('user_groups.*', 'roles.*')
.join('user_groups', 'user_groups.id', 'roles.user_group_id');

我希望这可以帮助某人。

【讨论】:

  • 如果这两个表的架构不同,请添加 .join('.user_groups', ....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-21
  • 2011-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-24
  • 2016-04-09
相关资源
最近更新 更多