在 Laravel 8 中,withCount()
方法用于在查询构建器中添加一个计数关系,它会返回关联模型的数量。如果你想要通过 withCount()
返回有答案的问题,你需要首先定义问题和答案之间的关系,然后使用 withCount()
来计算每个问题的答案数量。
withCount()
可以减少数据库查询次数,因为它会在单个查询中获取所有必要的数据。假设你有两个模型:Question
和 Answer
,它们之间是一对多的关系。
// Question.php
class Question extends Model
{
public function answers()
{
return $this->hasMany(Answer::class);
}
}
// Answer.php
class Answer extends Model
{
public function question()
{
return $this->belongsTo(Question::class);
}
}
现在,你可以使用 withCount()
来获取所有问题及其答案的数量:
$questionsWithAnswerCount = Question::withCount('answers')->get();
foreach ($questionsWithAnswerCount as $question) {
echo "Question ID: {$question->id}, Answer Count: {$question->answers_count}";
}
如果你在使用 withCount()
时遇到问题,比如没有得到预期的计数结果,可能的原因和解决方法如下:
hasMany
或 belongsTo
方法是否正确设置。toSql()
方法查看生成的 SQL 查询,确保它符合预期。$debugQuery = Question::withCount('answers')->toSql();
dd($debugQuery); // 查看生成的 SQL 语句
通过以上步骤,你应该能够解决在使用 withCount()
方法时遇到的问题,并成功返回有答案的问题列表及其答案数量。
极客说第一期
TVP技术夜未眠
Elastic 中国开发者大会
云+社区技术沙龙[第8期]
领取专属 10元无门槛券
手把手带您无忧上云