henk
henk

Reputation: 2848

How can I SUM up a column in relation to other Models where a parameter is met?

In my MYSQL database, there are three tables Author, Posts and Comments. The tables Posts and Comments have both the column 'votes'

the relation is as follows:

AuthorModel.hasMany(PostModel);
PostModel.belongsTo(AuthorModel);

PostModel.hasMany(CommentModel);
CommentModel.belongsTo(PostModel);

I am trying to sum the number of votes that comments received, which were posted under the postings of a specific author. I would expect to achieve this with the following query:

 var filtered_name = 'andy' //some filtered name

 Comment.sum('votes', {
              include: [{
                 model: Post,
                 attributes: [],
                 include: [{
                    model: Author,
                    attributes: [],
                    where: {name: {$like: filtered_name}}
                 }]
               }]
             })

But it returns the error: "ER_NON_UNIQ_ERROR: Column 'votes' in field list is ambiguous"

How can I resolve this?

The starting point is the parameter filtered_name while it is not important how the query is built, it is important that this parameter is used at the right position. For instance, I was trying to achieve this the other way round, by starting with the model Author where the parameter is met and trying to get the sum of the votes of Comments, but I was also not successful...

Upvotes: 1

Views: 795

Answers (1)

K Scandrett
K Scandrett

Reputation: 16540

Qualify the DB column name with the table name:

Comment.sum('Comments.votes', {
          include: [{
             model: Post,
             attributes: [],
             include: [{
                model: Author,
                attributes: [],
                where: {name: {$like: filtered_name}}
             }]
           }]
         })

Upvotes: 2

Related Questions