@@ -154,8 +154,9 @@ public function destroy($id)
154
154
public function apiIndex (Request $ request )
155
155
{
156
156
// Tạo truy vấn để lấy danh sách câu hỏi
157
- $ query = CauHoi::select ('id ' , 'noiDung ' , 'typeAudio ' , 'typeVideo ' , 'typeImage ' , 'doKho ' , 'monhoc_id ' );
158
-
157
+ $ query = CauHoi::select ('id ' , 'noiDung ' , 'typeAudio ' , 'typeVideo ' , 'typeImage ' , 'doKho ' , 'monhoc_id ' )
158
+ ->with ('monhoc ' ); // Eager load mối quan hệ với môn học
159
+
159
160
// Kiểm tra nếu có từ khóa tìm kiếm
160
161
if ($ request ->has ('search ' )) {
161
162
$ search = $ request ->input ('search ' ); // Lấy từ khóa tìm kiếm từ request
@@ -164,9 +165,38 @@ public function apiIndex(Request $request)
164
165
$ query ->where ('tenMonHoc ' , 'LIKE ' , "% $ search% " );
165
166
});
166
167
}
167
-
168
+
169
+ // Nếu có tham số 'monhoc', lọc kết quả theo 'monhoc_id'
170
+ if ($ request ->filled ('monhoc ' )) {
171
+ $ monhoc_id = $ request ->input ('monhoc ' );
172
+ $ query ->where ('monhoc_id ' , $ monhoc_id );
173
+ }
174
+
175
+ // Nếu có tham số 'doKho', lọc kết quả theo 'doKho'
176
+ if ($ request ->filled ('doKho ' )) {
177
+ $ doKho = $ request ->input ('doKho ' );
178
+ $ query ->where ('doKho ' , $ doKho );
179
+ }
180
+
181
+ // Nếu có tham số 'limit', giới hạn số lượng câu hỏi trả về
182
+ if ($ request ->filled ('limit ' )) {
183
+ $ limit = (int ) $ request ->input ('limit ' );
184
+ $ query ->limit ($ limit );
185
+ }
186
+
187
+ // Nếu có tham số 'random', sắp xếp ngẫu nhiên câu hỏi
188
+ if ($ request ->has ('random ' )) {
189
+ $ query ->inRandomOrder ();
190
+ }
191
+
168
192
// Thực hiện truy vấn và lấy kết quả
169
193
$ cauHois = $ query ->get ();
194
+
195
+ // nếu không có kết quả
196
+ if ($ cauHois ->isEmpty ()) {
197
+ return response ()->json (['message ' => 'No results found ' ], 404 );
198
+ }
199
+
170
200
// Trả về kết quả dưới dạng JSON với mã trạng thái 200
171
201
return response ()->json ($ cauHois , 200 );
172
202
}
0 commit comments