laravel hasMany() relation, average item from collection

Posted 2 months ago by jaheller

Short "preview". Each order can have a feedback. In case the product is physical, the feedback can have many packaging_feedbacks.

The packaging_feedbacks are some kind of relation to the packaging_feedback_details.

Models are:

feedback

public function packagingFeedbacks()
{
    return $this->hasManyThrough('App\PackagingFeedbackDetail', 'App\PackagingFeedback',
        'feedback_id', 'id', 'id', 'user_selection');
}

packaging_feedback_details
id|type_id(used to group the "names" for each feedback option)|name

packaging_feedbacks
id|feedback_id|user_selection

Now I would like to be able to get the average selection of the users for a physical product. I started by using:

    $result = Product::with('userFeedbacks.packagingFeedbacks')->where('id', 1)->first();

    $collection = collect();

    foreach ($result->userFeedbacks as $key) {

        foreach ($key->packagingFeedbacks as $skey) {
            $collection->push($skey);
        }
    }

    foreach ($collection->groupBy('type_id') as $key) {

        echo ($key->average('type_id'));
    }

This way returns float values, not the average user selection. Is there some better way, because I think it's not the cleverest way to do so.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.