[v4] How to get array of ids of a relation .with('tags') of belongsToMany? #3181
Answered
by
leandroaphermes
leandroaphermes
asked this question in
Help
-
I'm doing a fetch to get the tags a user has waiting for a structure like [{
id: 1,
....,
tags: [ 2, 5, 7, ... ]
}] // App/HTTP/UserController
const users = await User.query().with('tags').fetch() // App/Models/User
tags(){
return this.belongsToMany('App/Models/Tag').pivotTable('tag_user')
} |
Beta Was this translation helpful? Give feedback.
Answered by
leandroaphermes
Mar 7, 2023
Replies: 1 comment
-
I managed to make the query return only the ids of the markers without using relationship in the select Solution: // App/HTTP/UserController
await User.query().select([
"id",
"name",
Database.raw(
`(
SELECT JSON_ARRAYAGG(tag_user.tag_id) FROM tag_user WHERE tag_user.user_id= user.id
) as tag_ids`
),
]).fetch() // App/Models/User
class User {
getTagIds(value) {
return value ? JSON.parse(value) : [];
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
leandroaphermes
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I managed to make the query return only the ids of the markers without using relationship in the select
Solution: