(Using PostgreSQL) So, I have these (User and Vote) Objection.js models:
const { Model } = require('objection');
class User extends Model {
static get tableName() {
return 'users';
}
static get relationMappings() {
return {
posts: {
relation: Model.HasManyRelation,
modelClass: require('./Post'),
join: {
from: 'users.id',
to: 'posts.userId',
},
},
comments: {
relation: Model.HasManyRelation,
modelClass: require('./Comment'),
join: {
from: 'users.id',
to: 'comments.userId'
}
},
votes: {
relation: Model.HasManyRelation,
modelClass: require('./Vote'),
join: {
from: 'users.id',
to: 'votes.userId'
}
}
};
}
}
module.exports = User;
const { Model } = require('objection');
class Vote extends Model {
static get tableName () { return 'votes' }
static get relationalMappings () {
return {
user: {
relation: Model.BelongsToOneRelation,
modelClass: require('./User'),
join: {
from: 'votes.userId',
to: 'users.id'
}
},
post: {
relation: Model.BelongsToOneRelation,
modelClass: require('./Post'),
join: {
from: 'votes.postId',
to: 'posts.id'
}
}
}
}
}
module.exports = Vote;
The psql command \d users
returns:
Table "public.users"
Column | Type | Collation | Nullable | Default
-------------+------------------------+-----------+----------+-------------------
id | uuid | | not null | gen_random_uuid()
username | character varying(128) | | not null |
displayname | character varying(128) | | not null |
email | character varying(256) | | not null |
description | character varying(256) | | |
password | character varying(512) | | not null |
Indexes:
"users_pkey" PRIMARY KEY, btree (id)
"users_id_index" btree (id)
Referenced by:
TABLE "comments" CONSTRAINT "comments_userid_foreign" FOREIGN KEY ("userId") REFERENCES users(id)
TABLE "posts" CONSTRAINT "posts_userid_foreign" FOREIGN KEY ("userId") REFERENCES users(id)
TABLE "votes" CONSTRAINT "votes_userid_foreign" FOREIGN KEY ("userId") REFERENCES users(id)
And the psql command \d votes
returns:
Table "public.votes"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+-------------------
id | uuid | | not null | gen_random_uuid()
userId | uuid | | not null |
postId | uuid | | not null |
up | boolean | | not null |
down | boolean | | not null |
Indexes:
"votes_pkey" PRIMARY KEY, btree (id)
"votes_id_index" btree (id)
Foreign-key constraints:
"votes_postid_foreign" FOREIGN KEY ("postId") REFERENCES posts(id)
"votes_userid_foreign" FOREIGN KEY ("userId") REFERENCES users(id)
What i would like to do is use some sort of Model class method (on the class User) to set the properties upvotes
(number of Votes with up
set to true), downvotes
(number of Votes with down
set to true) and balance
(upvotes - downvotes
).