-
-
Save Bunix/415b8a5ad15e9470402ec715922b51e4 to your computer and use it in GitHub Desktop.
Calculate Post Rating
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Jobs; | |
use App\Entities\Review; | |
use Illuminate\Bus\Queueable; | |
use Illuminate\Queue\SerializesModels; | |
use Illuminate\Queue\InteractsWithQueue; | |
use Illuminate\Contracts\Queue\ShouldQueue; | |
use Illuminate\Foundation\Bus\Dispatchable; | |
use Illuminate\Support\Facades\DB; | |
class CalculatePostRating implements ShouldQueue | |
{ | |
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; | |
/** | |
* @var \App\Entities\Review | |
*/ | |
protected $review; | |
/** | |
* CalculatePostRating constructor. | |
* | |
* @param \App\Entities\Review $review | |
*/ | |
public function __construct(Review $review) | |
{ | |
$this->review = $review; | |
} | |
/** | |
* Execute the job. | |
* | |
* @return void | |
*/ | |
public function handle() | |
{ | |
$rating1 = DB::table('reviews')->where(['post_id' => $this->review->post_id, 'rating' => 1])->count(); | |
$rating2 = DB::table('reviews')->where(['post_id' => $this->review->post_id, 'rating' => 2])->count(); | |
$rating3 = DB::table('reviews')->where(['post_id' => $this->review->post_id, 'rating' => 3])->count(); | |
$rating4 = DB::table('reviews')->where(['post_id' => $this->review->post_id, 'rating' => 4])->count(); | |
$rating5 = DB::table('reviews')->where(['post_id' => $this->review->post_id, 'rating' => 5])->count(); | |
$totals = $rating1 + $rating2 + $rating3 + $rating4 + $rating5; | |
$averages = ($rating5*5) + ($rating4*4) + ($rating3*3) + ($rating2*2) + ($rating1*1); | |
$overall = round($averages / $totals); | |
DB::table('posts')->where('id', $this->review->post_id)->update(['rating' => $overall]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment