B
B
BonBon Slick2020-06-29 20:42:04
Doctrine ORM
BonBon Slick, 2020-06-29 20:42:04

Calculate average relation field?

https://www.doctrine-project.org/projects/doctrine...

$query->addSelect(['m', $query->expr()->avg('r.distance') .  ' as distance'])
                  ->from(Member::class, 'm')
            ;

        $query->join('m.runs', 'r');

        $query->addOrderBy($query->expr()->avg('r.distance'), 'ASC');

        $result =$query->getQuery()->getResult();

        foreach ($result as $item) {
            dump($item['distance']);
        }
        die;

There are 3 entries in the database.
1 user walked a distance of 2 km for 1 run.
The 2nd user walked 2 and 3 km for 2 runs.
That is, the average score of participant 1 = 2, participant 2 = 2.5, and teams 2 + 3 + 2 =

3.5

I know that you can pull out entities and calculate their distance in essence, like this , but this is a hard crutch.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BonBon Slick, 2020-06-29
@BonBonSlick

Be sure to add
$query->addGroupBy('m.id');
before sorting, without this it gave an incomprehensible result, 1 record of the 2nd user and 3 km, instead of 2 users and averages

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question