Objection.js如何根据关系过滤模型

问题描述 投票:0回答:1

所以我一直试图找到一种方法在objection.js中执行以下sql

SELECT u.user_id, u.profile_photo_name, u.first_name, u.last_name, COUNT(*) AS count FROM users AS u INNER JOIN post_users AS pu ON (u.user_id = pu.user_id) WHERE u.organization_id = 686 GROUP BY user_id ORDER BY count DESC LIMIT 1

这是我到目前为止所做的...但不能以这种方式使用$ relatedQuery

return await User.$relatedQuery('recognitions')
.where('organization_id', organizationID)
.select(
    'user_id',
    'profile_photo_name',
    'first_name',
    'last_name',
    raw('COUNT(*) as count')
)
.groupBy('user_id')
.orderBy('count', 'desc')
.limit(1)

这是认可关系:

            recognitions: {
                relation: Model.ManyToManyRelation,
                modelClass: Post,
                join: {
                    from: 'users.user_id',
                    through: {
                        from: 'post_users.user_id',
                        to: 'post_users.post_id',
                    },
                    to: 'posts.post_id'
                }
            },
mysql node.js objection.js
1个回答
0
投票

不得不使用joinRelation,所以也使用first()而不是limit(1)来获得单个对象而不是长度为1的数组

return await User.query()
.joinRelation('recognitions')
.where('organization_id', organizationID)
.select(
    'user_id',
    'profile_photo_name',
    'first_name',
    'last_name',
    raw('COUNT(*) as count')
)
.groupBy('user_id')
.orderBy('count', 'desc')
.first()
© www.soinside.com 2019 - 2024. All rights reserved.