Laravel用雄辩的方法获取不同用户的数据平均值

时间:2019-07-12 06:33:39

标签: laravel

我完成了一项功能,可以计算给不同用户的分数平均值。平均值计算不同用户分数的平均值不同。

我希望在雄辩的帮助下完成此功能,以便可以使用此模型的关系

    $data = \DB::table('cleaning_scores')
                ->select(\DB::raw('avg(score) as avg, user_id'))
                ->groupBy('user_id')->orderBy('avg','DESC')
                ->get();  

这是我的CleaningScore.php模型

    <?php

      namespace App;

     use Illuminate\Database\Eloquent\Model;

     class CleaningScore extends Model
     {
         protected $fillable = ['user_id','score','giver_id'];

         public function users()
         {
            return $this->belongsTo(User::class , 'user_id');
         }
         public function givers()
         {
            return $this->belongsTo(User::class , 'giver_id');
         }
     }

这是用户模型

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use Notifiable,HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','room_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function rooms()
    {
        return $this->belongsTo(Room::class , 'room_id');
    }

    public function scores()
    {
        return $this->hasMany(Score::class);
    }

    public function cleaning_scores()
    {
        return $this->hasMany(CleaningScore::class);
    }

    public function own_rooms()
    {
        return $this->hasMany(Room::class);
    }

    public function own_scores()
    {
        return $this->hasMany(CleaningScore::class);
    }

    public function rankings()
    {
        return $this->hasOne(Ranking::class);
    }
}

2 个答案:

答案 0 :(得分:0)

这是您想要的吗?用模型进行雄辩的查询?

$data = CleaningScore::select('user_id', \DB::raw('avg(score) as avg'))
            ->groupBy('user_id')->orderBy('avg','DESC')
            ->get();

我希望对您有帮助

答案 1 :(得分:0)

对于单个用户“平均值”,您可以使用类似这样的高雅关系:

  User::find(2)->cleaning_scores()->avg('score')

多个用户的平均值:

CleaningScore::select(\DB::raw('user_id,AVG(score) as scoreavg'))
            ->groupBy('user_id')
            ->orderBy('scoreavg','DESC')
            ->get();