按Laravel中的selectRaw关系排序(计算的数量,总和......)

时间:2015-12-05 14:31:40

标签: php sorting laravel eloquent relationship

我有Question模型,其中包含morphMany AnswerAnswer还有morphMany AnswerRating

我添加了计算和加载Answer计数和Answer评级总和的关系:

<?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);
}
}

现在我想知道如何加载Question Answer已按照答案计数,评分,created_at等排序

是否可以使用已经热切的加载answersCountRelationratingSumRelation来完成?

或者我必须在Question->with(['answers' => function ($q) ...

中再做一次请求

Thx!

0 个答案:

没有答案