Skip to content
Advertisement

Laravel add calculate the sum where the value is in another table

Basically i have two tables. answers and choices . In my choices table, I got a column choices.value which is has values 0-4. My current query like this

JavaScript

My current response is like this

JavaScript

how do i add the values so that my result will be like this

JavaScript

I tried doing DB::raw(SUM(choices.values)as score) but i get a large amount. I guess its adding all the choices values from the choices table and not in the answers.

My answers db which i only select the answers of the user = 2. I limit to 5

JavaScript

My choices table, I only select questions 1 and 2 and their choices.

JavaScript

Also i want to make a new table named scores and the columns will be the result of what i want. I want to add the choices.values in the answer in every answers.user_id so that when i view the scores table, it will display the total score in every user or when the user finished answering all 21 questions because i only got 21 items it will automatically add in the scores table. Could I possibly do that?. Is it okay to add a value in the answers table based in the choice_id? That is what im thinking but I think its redundant since the choice_id is there already. Thanks in advance.

PS: Tried writing these queries but always get 441 which is the total value of all the choices in the choices table

JavaScript

Advertisement

Answer

Currently you are only matching to a choice but you need to match the choice as well as the question.

I found this after seeng each choices.question_id had choices 1, 2, 3 and 4 in a slack conversation. I didn’t know until I actually saw a screenshot of the choices table.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement