[英]Better way to retrieve data from multiple table using Laravel's Eloquent
在我的測驗應用程序上,我想讓我的代碼更具可擴展性,但我很困惑如何優化它,而這個最令人困惑.. 我有四個表
1.Question Table
2.QuestionOption Table
3.QuestionImage Table
4.QuestionSolutionImage Table
問題表與下表中的所有外鍵 QuestionId 鏈接
現在為了獲取 questionData 我執行這段代碼
$builder = Question::where('TestId', $_testId);
$data = $builder->with(['questionOptions' => function ($query) {
$query->where('Status',1)
->select(['QuestionId', 'id', 'optionText', 'rank', 'isAnswer', 'timeStamp']);
}]) ->with(['questionImages' => function ($query) {
$query->where('Status',1)
->select(['QuestionId', 'id', 'imagePath', 'thumbPath', 'rank', 'timeStamp']);
}])->with(['solutionImages' => function ($query) {
$query->where('Status',1)
->select(['QuestionId', 'id', 'imagePath', 'thumbPath', 'rank', 'timeStamp']);
}]);
$data = $builder->select([
'Id', 'uid', 'type', 'rank', 'questionText', 'totalMarks', 'negativeMark as negativeMarks', 'note', 'solutionText', 'status', 'timeStamp',
])->get()->toArray();
我得到了這個 output
[
{
"Id": 1,
"uid": "123456789098760",
"type": "multiple",
"rank": 1,
"questionText": "2 + 2 = ?",
"totalMarks": 5,
"negativeMarks": 2,
"note": null,
"solutionText": null,
"status": "active",
"timeStamp": "2020-11-17 11:42:31",
"questionOptions": [
{
"QuestionId": 1,
"id": 1,
"optionText": "5",
"rank": 1,
"isAnswer": "no",
"timeStamp": "2020-11-17 11:42:31"
},
{
"QuestionId": 1,
"id": 2,
"optionText": "4",
"rank": 2,
"isAnswer": "yes",
"timeStamp": "2020-11-17 11:42:31"
},
{
"QuestionId": 1,
"id": 3,
"optionText": "four",
"rank": 3,
"isAnswer": "yes",
"timeStamp": "2020-11-17 11:42:31"
},
{
"QuestionId": 1,
"id": 4,
"optionText": "7",
"rank": 4,
"isAnswer": "no",
"timeStamp": "2020-11-17 11:42:31"
}
],
"questionImages": [
{
"QuestionId": 1,
"id": 1,
"imagePath": "12345678",
"thumbPath": "thumbPath",
"rank": 10,
"timeStamp": "2020-11-17 11:42:31"
},
],
"solutionImages": [
{
"QuestionId": 1,
"id": 1,
"imagePath": "storage/app/solution/image/a7bBSNRkgy.jpg",
"thumbPath": "storage/app/solution/thumb/a7bBSNRkgy.jpg",
"rank": 10,
"timeStamp": "2020-12-04 10:32:49"
}
]
}
]
它看起來很完美並且工作正常,但從現在開始,隨着用戶增加這個問題 api 對 DB 的影響太大,導致 DB 上的連接問題太多,我也在 DB 上增加了這個問題。 但我的實際觀點是我是否可以優化此代碼並以更好的方式執行此代碼,因為此代碼會導致對 DB 的多次訪問。 任何幫助將不勝感激,如果有什么誤解,請詢問。 謝謝 !!
您可以嘗試將塊與查詢生成器一起使用。 如果您將 eloquent 用於需要處理結果的大數據,那么原始 sql 比 eloquent 快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.