Objection.js如何基于关系过滤模型

时间:2019-03-15 17:37:10

标签: mysql node.js objection.js

所以我一直试图在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'
                }
            },

1 个答案:

答案 0 :(得分:0)

必须使用select s.Url, sum(case when su.type = 'member' then 1 else 0 end) as members, sum(case when su.type = 'owners' then 1 else 0 end) as owners, from sites s left join siteusers su on s.siteid = su.siteid where su.type in ('member', 'owners') group by s.url; 代替joinRelation而不是first()来获得单个对象而不是长度为1的数组

limit(1)