Making complex SQL query using Eloquent, need assistance

时间:2015-06-25 09:57:57

标签: sql laravel eloquent

I am working with an api call where you are supposed to search for a 'survey' and sum up the different answers (located in other tabels). I am fairly new to eloquent and this is a little to complicated for me so I need some help.

There is 4 different tables with data, Survey, SurveyAnswerSets, Survey_X, Survey_XY.

What I want to do is search for surveys using a title, startDate and endDate. From the fetched surveys I need to fetch additional information from the 3 other tabels. I think I am supposed to use eager loading.

This is the datafields I am supposed to fetch:

"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

The easy part of selecting the correct surveys I have done:

$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();

but this leaves the tricky parts where I need help or advice how to start.

1 个答案:

答案 0 :(得分:1)

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

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

User Name: <input required type="text"  ng-model="uname" name="uname" id="uname" unique-field  /><br/>
    <span style="color:red" ng-show="form_add.uname.$dirty && form_add.uname.$invalid">
        <span ng-show="form_add.uname.$error.required">User Name is required.</span>    
        <span ng-show="form_add.uname.$error.uniqueField">User Name already exists.</span>
    </span>

这假设您正确配置了relationships

相关问题