Hi,
I have three columns [ stores - rating_average - ratings ], if a user rated a store a new record will be added to the ratings table [ store_id -rating - guest_id - timestamps ] after that it will count all the ratings for that store id and crate or update the rating_average [ store_id - average - ratersCount ].
Now when the user click and view a listing (store) I make an ajax call after 10s of page fully load to the following function at ** RatingController ** to determine if the listing is trending or not.
#RatingController
public function show(int $id): \Illuminate\Http\JsonResponse
{
$store = Store::where('id', $id)->firstOrFail();
$last_period = $store->ratings()->selectRaw('AVG(ratings.rating) as aggregate')->where('created_at', '<=', Carbon::now()->subDay(1) )->pluck('aggregate')->shift();
$this_period = $store->ratings()->selectRaw('AVG(ratings.rating) as aggregate')->where('created_at', '>=', Carbon::today() )->pluck('aggregate')->shift();
return response()->json(($last_period > $this_period ? false : ( $last_period < $this_period ? true : 0)), 200);
}
Now what I want to do is to add a Boolean column to rating_average and name it trending so I can query all the trending stores (listings) but I don't when to call the function that do the calculation to determine if the store is trending!
Is there any more simple way to do this?
User can rate a listing and I could increment the counter of people who have rated that listing and add an avg rating and compare average of ratings on two dates and see if the average rating is higher than the previous day.
#store model relationships
public function ratings(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(Rating::class, 'store_id');
}
public function rating_average(): \Illuminate\Database\Eloquent\Relations\HasOne
{
return $this->hasOne(ratingAverage::class, 'store_id');
}
#ratingAverage model relationships
public function store(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Store::class,'store_id');
}
# migrations
Schema::create('rating_average', function (Blueprint $table) {
$table->id();
$table->bigInteger('store_id')->unsigned()->unique();
$table->decimal('average')->unsigned();
$table->bigInteger('ratersCount');
$table->foreign('store_id')->references('id')->on('stores')->onDelete('cascade');
$table->timestamps();
});
#Rating model relationships
public function stores(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Store::class,'store_id');
}
#migration
Schema::create('ratings', function (Blueprint $table) {
$table->id();
$table->bigInteger('store_id')->unsigned();
$table->Integer('rating');
$table->string('guest_id')->unsigned();
$table->foreign('store_id')->references('id')->on('stores')->onDelete('cascade');
$table->timestamps();
});