【问题标题】:Making complex SQL query using Eloquent, need assistance使用 Eloquent 进行复杂的 SQL 查询,需要帮助
【发布时间】:2015-06-25 09:57:56
【问题描述】:

我正在使用 api 调用,您应该在其中搜索“调查”并总结不同的答案(位于其他表格中)。我是 eloquent 的新手,这对我来说有点复杂,所以我需要一些帮助。

有 4 个不同的数据表,Survey、SurveyAnswerSets、Survey_X、Survey_XY。

我想做的是使用标题、startDate 和 endDate 搜索调查。从获取的调查中,我需要从其他 3 个表格中获取更多信息。我想我应该使用急切加载。

这是我应该获取的数据字段:

"surveyId": Survey.surveyId
"title": Survey.title
"startDate": Survey.startDate
"endDate": Survey.endDate
"targetReplies": Survey.targetReplies
"repliesExposed": Number of rows in SurveyAnswerSets where surveyId = surveyId and isRefGroup = 0 and isComplete = 1
"repliesControl": Number of rows in from SurveyAnswerSets where surveyId = surveyId and isRefGroup = 1 and isComplete = 1
"repliesTotal": Number of rows in from SurveyAnswerSets where surveyId = surveyId and isComplete = 1
"useRefGroup": Survey.useRefGroup
"orderId": Survey.orderId
"surveyXIds": Survey_X where surveyId = surveyId
"originalXYIds": Survey_XY where surveyId = surveyId

选择我所做的正确调查的简单部分:

$columns = array('surveyId', 'title', 'startDate', 'endDate', 'isTemplate');

$surveys = Survey::notemplate()
            ->where('title', 'LIKE', "%$name%")
            ->where('startDate', '<=', Carbon::now()->toDateString())
            ->where('endDate', '>', Carbon::now()->toDateString())
            ->select($columns)
            ->get();

但这留下了我需要帮助或建议如何开始的棘手部分。

【问题讨论】:

  • 如果您想在一次访问数据库中获得结果,我建议您使用原始 SQL 查询,而不是尝试使用 Eloquent 来表达它。

标签: sql laravel eloquent


【解决方案1】:

预加载只是一种优化(防止许多 SQL 查询)。

您无需编写更多查询:只需使用对象适当的方法即可。

foreach($surveys as $survey){
  $repliesExposed = $survey->answers()->where(...)->count();
}

这假设您正确配置了relationships

【讨论】:

  • 所以假设我想过滤答案,计算行数并将其分配给每个surveyId的列(如repliesExposed)我在查询中过滤掉而不为每个surveyId进行新的数据库调用.我该怎么做?
  • 我认为您应该首先尝试使您的代码执行您需要的操作(即使它需要大量的数据库调用),然后如果出现问题,请尝试减少查询次数。
猜你喜欢
  • 2016-12-18
  • 1970-01-01
  • 2013-06-19
  • 2020-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-28
相关资源
最近更新 更多