Objection.js 如何根据关系过滤模型
Objection.js how to filter a model based on relationship
所以我一直在尝试找到一种方法来在 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'
}
},
不得不使用 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()
所以我一直在尝试找到一种方法来在 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'
}
},
不得不使用 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()