使用Laravel Eloquent ORM系统,我创建了以下模型:
/**
* @property int $id
*/
class Category extends Model
{
public function questions()
{
return $this->hasMany(Question::class);
}
}
/**
* @property int $id
* @property int $category_id
*/
class Question extends Model
{
public function answers()
{
return $this->hasMany(Answer::class);
}
}
/**
* @property int $id
* @property int $question_id
*/
class Answer extends Model {}
现在我正试图加载以下值:
我已经使用以下代码解决了1和2问题:
$categories = Category
::withCount('questions')
->get();
$vars = ['categories' => $categories];
对于第三个值,我尝试了类似的操作(不起作用):
$categories = Category
::withCount(['questions', 'questions as answered_questions' => function ($query) {
$query->select()
->from('answers')
->whereRaw('answers.question_id = questions.id');
}])
->get();
如何有效地计算出具有一个或多个答案的问题数量?
答案 0 :(得分:1)
您可以尝试has
类别模型
class Category extends Model
{
public function questions()
{
return $this->hasMany(Question::class);
}
function answers()
{
return $this->hasManyThrough(Answer::class, Question::class);
}
}
获取数据
$categories = Category::withCount('questions')->has('answers')->get();
foreach($categories as $category){
$category->name." - ". $category->questions_count;
}
这里questions_count
是针对该类别的至少一个答案的总问题
答案 1 :(得分:1)
在@rkj的帮助下,我发现了has
函数。这样我就可以创建以下解决方案:
$categories = Category
::withCount(['questions', 'questions as answered_questions' => function ($query) {
$query->has('answers');
}])
->get();
现在我可以使用$category->questions_count
和$category->answered_questions
,这正是我所需要的。