简体   繁体   中英

how to use sum method eloquent laravel

how to get a sum of value in like model in laravel 8

Like Model

    public function likeable() {
        return $this->morphTo('likeable', 'likeable_type', 'likeable_id');
    }

Post Model

    public function likes() {
        return $this->morphMany('App\Models\Like', 'likeable');
    }

Main Controller

        $posts = Post::withCount('comments')
            ->with('likes')
            ->with('channel')
            ->with('user')
            ->where('posts.hide', '=', '0')
            ->get()
            ->toJson();

Like migrate

        Schema::create('likes', function (Blueprint $table) {
            ...
            $table->integer('value'); // like value
            $table->string('likeable_type', 50);
            $table->integer('likeable_id');
            ...
        });

You can get the sum of value from the Like model like this

Like::sum('value');

If you want to sum only like for a specific likeable you can add more filtering like this

Like::where('likeable-type, 'App\Models\Like')->sum('value');

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