我有Question
模型,其中包含morphMany Answer
。 Answer
还有morphMany Answer
和Rating
我添加了计算和加载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等排序
是否可以使用已经热切的加载answersCountRelation
或ratingSumRelation
来完成?
或者我必须在Question->with(['answers' => function ($q) ...
Thx!