mercredi 27 septembre 2017

Return zero instead of empty array in Laraval aggregated relation

I'm using Laravel 5.4 and I have a Model for stores in which has a related table called stores_ratings which has (store_id, rating) columns. I'm trying to get the average value and I got some luck doing this:

public function ratings(){
    return $this->hasMany(StoresRating::class);
}

public function avgRating()
{
    return $this->ratings()->selectRaw('avg(rating) as aggregate, store_id')->groupBy('store_id');
}

This works fine, however, I need to return zero in aggregate if the store has no ratings in the database.

I tried this as well but no luck, I feel like this function is being ignored, mostly for any type of array.

public function getAvgRatingAttribute()
{
    if ( ! array_key_exists('avgRating', $this->relations)) {
       $this->load('avgRating');
    }

    $relation = $this->getRelation('avgRating')->first();

    return ($relation) ? $relation->aggregate : null;
}

Sample output:

"ratings": [
                {
                    "id": 8,
                    "user_id": 18,
                    "store_id": 81,
                    "rating": 4,
                    "comment": "good one",
                    "approved": 0,
                    "created_at": "2017-09-20 08:01:09",
                    "updated_at": "2017-09-20 08:01:09"
                }
            ],
            "avg_rating": [
                {
                    "aggregate": "4.0000",
                    "store_id": 81
                }
            ]

Output of model without related data:

"ratings": [],
"avg_rating": [],

I'm trying to achieve something like this if no related data was found:

"ratings": [],
"avg_rating": [{
"aggregate": 0
}],

thank you.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire