Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 按Laravel中的selectRaw关系排序(计算计数、总和…)_Php_Sorting_Laravel_Eloquent_Relationship - Fatal编程技术网

Php 按Laravel中的selectRaw关系排序(计算计数、总和…)

Php 按Laravel中的selectRaw关系排序(计算计数、总和…),php,sorting,laravel,eloquent,relationship,Php,Sorting,Laravel,Eloquent,Relationship,我有一个问题模型,它有许多答案答案也有许多答案和评分 我添加了计算和加载Answercount和Answerrating sum的关系: <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Auth; use App\Facades\AuthManager; class Answer extends Model { protected $w

我有一个
问题
模型,它有许多
答案
<代码>答案也有许多
答案
评分

我添加了计算和加载
Answer
count和
Answer
rating sum的关系:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use App\Facades\AuthManager;

class Answer extends Model {
protected $with = [
        'user',
        'cards',
        'answers.user',
        'answersCountRelation',
        'ratingSumRelation'
];
protected $fillable = [
        'text',
        'user_id'
];

public function answerable() {
    return $this->morphTo();
}

public function user() {
    return $this->belongsTo(User::class);
}

public function answers() {
    return $this->morphMany(Answer::class, 'answerable');
}

public function reports() {
    return $this->morphMany(Report::class, 'reportable');
}

public function cards() {
    return $this->hasMany(Card::class);
}

public function ratings() {
    return $this->hasMany(Rating::class);
}

public function hasReported(User $user) {
    return ($user != null && $this->reports()->where([
            'user_id' => $user->id
    ])->first() != null);
}

public function hasRated(User $user) {
    return ($user != null && $this->ratings()->where([
            'user_id' => $user->id
    ])->first() != null);
}

public function answersCountRelation() {
    return $this->answers()->selectRaw('answerable_id, count(*) as count')->groupBy('answerable_id');
}

public function getAnswersCountAttribute() {
    return ($this->answersCountRelation->first() ? $this->answersCountRelation->first()->count : 0);
}

public function ratingSumRelation() {
    return $this->ratings()->selectRaw('answer_id, SUM(power) as sum')->groupBy('answer_id');
}

public function getRatingSumAttribute() {
    return ($this->ratingSumRelation->first() ? $this->ratingSumRelation->first()->sum : 0);
}
}