I
I
iamdivine2021-12-01 13:07:20
Laravel
iamdivine, 2021-12-01 13:07:20

How to count the number of records in a relation?

There are 2 tables. 1 contains the vote itself, and the other contains the statistics of the votes
61a74905754c0857776416.png
.
The code that is currently

public function convVote() {
        return $this->hasMany(conv_voting::class, 'conv_id');
    }

    public function countVoteStats($count_id) {
        return self::find($count_id)->with('convVote')->get();
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-12-01
@iamdivine

public function countVoteStats($count_id) {
    $model = self::find($count_id);

    return [
        'agree' => $model->convVote->sum('agree'),
        'disagree' => $model->convVote->sum('disagree'),
        'neutral' => $model->convVote->sum('neutral'),
    ];
}

Or three separate requests, but without loading extra fields and entities:
public function countVoteStats($count_id) {
    $query = conv_voting::where('conv_id', $count_id);

    return [
        'agree' => $query->sum('agree'),
        'disagree' => $query->sum('disagree'),
        'neutral' => $query->sum('neutral'),
    ];
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question