1

I'm trying to calculate a 'loyalty' score on Users. I have an Entries field history, with Entries like 2023, 2022, 2021 etc.

I want to calculate the number of consecutive years, going backward from the current year. So for example, a user with 2023, 2022, 2021 would have a loyalty score of 3. A user with 2022 and 2021 would have a loyalty score of 0 because they don't have a 2023 Membership. Should they buy one, they would immediately have 3 years of loyalty.

One additional problem is that these entries might not be in order in the field. They might be in order like 2019, 2022, 2020, 2023, 2021.

I previously had this working with tags, but with 4.4 and 5 coming soon I want to Entrify everything.

Here's my attempt based on that, but my loyalty value is only ever 0 or 1. I guess the previousYear part isn't working. Does anyone have ideas on fixing this or a better way to do it?

$currentYear = date('Y');
$previousYear = null;
$history = $user->history->all();
$loyalty = 0;
foreach ($history as $item) {
    $year = $item->title;
    if ($year === $currentYear) {
        $loyalty++;
        $previousYear = $year - 1;
    } elseif ($previousYear !== null && $year === $previousYear) {
        $loyalty++;
        $previousYear = $year - 1;
    }
}
$user->setFieldValue('loyalty', $loyalty);
supazu
  • 576
  • 4
  • 12

1 Answers1

2

You can modify the query to select only the title (since you don't need anything else) and sort the results by title in descending order:

$history = $user->history->orderBy('title DESC')->select('title')->column();

This will give you an array of years (assuming the titles only include the year and nothing else) in descending order. Then you can simplify the logic to increase the loyalty count for every consecutive year that's included in the array, starting from the current one. For example:

$loyalty = 0;
$year = (int) date('Y');
while (in_array($year, $history)) {
    $loyalty++;
    $year--;
}
MoritzLost
  • 11,215
  • 5
  • 22