mercredi 1 juillet 2020

Laravel DB get sum of column of left joined table (sum of thumbs up/down against a post)

I have a reviews site, and users can thumbs up or thumbs down a review. The reviews table existed because I am using a Laravel boilerplate that I found. I've added the thumbs table using migrate and created a model and controller.

These are the two tables in question.

reviews
+----+-----------------+------------+-----------+---------+
| id | review_constant | title      | publish   | etc...  |
+----+-----------------+------------+-----------+---------+
| 1  | 1               | Test       | published | blah    |
| 2  | 2               | Test2      | old       | blah    |
| 3  | 2               | Test2 Edit | published | blah    |
+----+-------+---------+------------+-----------+---------+

review_thumbs
+----+---------+-----------------+-------+
| id | user_id | review_constant | thumb |
+----+---------+-----------------+-------+
| 1  |  12     |   2             |  1    |
| 2  |  10     |   2             | -1    |
| 3  |  8      |   2             |  1    |
| 4  |  17     |   2             |  1    |
+----+---------+-----------------+-------+

review_constant is the original reviews.id which is passed to any edits for a single review. We're only interested in rows where publish = 'published'.

I can get each published review no problem.

Reviews::where( 'publish', 'published' )

But I also want the SUM of thumbs that match that review's review_constant, which I can do with SQL

SELECT reviews.id, reviews.review_title, rt.review_constant, rt.thumbs
FROM reviews 
LEFT JOIN ( 
    SELECT review_constant, SUM(thumb) AS thumbs FROM review_thumbs 
) AS rt ON (rt.review_constant = reviews.review_constant)
where reviews.publish = 'published'

I'm struggling to do this in Laravel. I found some instructions telling me I need to add relationships like this

class ReviewThumbs extends Model
{
    public function reviews()
    {
        return $this->belongsTo(Posts::class, 'id', 'post_id');
    }
    ...

}

class Review extends Model
{

    public function reviewThumbs(){
        return $this->hasMany(ReviewThumbs::class, 'id', 'post_id');
    }
    ...
}

and then I can do this Reviews::where( 'publish', 'published' )->with('review_thumbs'), and that I should then be able to use it in a blade template. I don't know the correct syntax, and everything I do try throws an error. I've tried sum(), count(), using getReviewThumbsAttribute and I'm lost.

@if ($review->thumbs->sum() > 0 ) 
    +
@else
    
@endif

What should be in place of $review->thumbs->sum() and if I need to, what methods do I need to add to the PHP classes?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire