Skip to content
Advertisement

(Laravel) Multiple counts, group by on same table with one query

I have two tables. I would like to get the values of the counts of these two rows (attacker, victim) from the first table and their respective userid from the second table, if possible.

Table1:

Table2:

So far I only managed to get the values of the counts of rows attacker and victim but I achieved it using two separate queries. Is it possible to do this with just one query?

Basically what I am aiming for is to get something like this in the end:

UPDATE:

After some time I managed to get name + victims and name + attackers but separate by using the code below:

Advertisement

Answer

After some hours of researching I think I somehow managed to find a solution. I just had to use relationships.

On Table 2 Model:

then I used the following code to get the results I wanted:

I’ll also post the RAW SQL query incase anyone could benefit from it

If anyone knows how to further improve this query for performance, please let me know.

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