简体   繁体   中英

How can I write this query with Eloquent

Let's say I have a method like this:

public function scopeWithLikes(Builder $query)
    {
        $query->leftJoinSub(
            'select likeable_id, sum(liked) likes, sum(!liked) dislikes from likes group by likeable_id',
        );
    }

My question is, how can I rewrite this query with Eloquent for my Laravel project?

From what I understood I think this is what you are looking for, try it and tell me:


$orders = DB::table('likes')
                ->select('likeable_id', DB::raw('SUM(liked) as likes'), DB::raw('SUM(!liked) as dislikes'))
                ->groupBy('likeable_id')
                ->get();

You can get more information from the laravel Database documentation Query Builder here:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM