就我而言,我正在根据学院名称,地点和课程开设搜索培训机构
我有3张桌子
public function locations()
{
return $this->hasMany(Location::class);
}
public function courses()
{
return $this->hasMany(Course::class);
}
我创建了3个表格之间的关系
学院模型:
public function institute()
{
return $this->belongsTo(Institute::class);
}
课程模型:
public function institute()
{
return $this->belongsTo(Institute::class);
}
位置模型:
public function filter(Request $request)
{
$institute = (new Institute)->newQuery();
// Search for a user based on their institute.
if ($request->has('institute_name')) {
$institute->where('institute_name', $request->input('institute_name'));
}
// Search for a user based on their course_name.
if ($request->has('course_name')) {
$institute->whereHas('courses', function ($query) use ($request) {
$query->where('courses.course_name', $request->input('course_name'));
});
}
// Search for a user based on their course_name.
if ($request->has('location_name')) {
$institute->whereHas('locations', function ($query) use ($request) {
$query->where('locations.location_name', $request->input('location_name'));
});
}
return response()->json($institute->get());
}
所以我试过下面的代码
[
{
"id": 2,
"institute_name": "qspider",
"institute_contact_number": "9903456789",
"institute_email": "qspider@gmail.com",
"status": "1",
}
]
从上面的代码我可以过滤数据,但它只显示机构表数据,如下所示。
SELECT Subject.ID, Subject.Description, Max(DataSets.ID) AS ID_DataSets
FROM Subject
INNER JOIN DataSets ON Subject.Description = DataSets.Subject.Value
GROUP BY Subject.ID, Subject.Description;
但我需要的是当我使用course_name或instute_name进行搜索时,我需要从institues表,课程和位置表中获取数据。有人可以帮忙吗?
答案 0 :(得分:1)
急切加载if语句中的关系。
// Search for a user based on their course_name.
if ($request->has('course_name')) {
$institute->whereHas('courses', function ($query) use ($request) {
$query->where('courses.course_name', $request->input('course_name'));
})
->with('courses); // <<<<<< add this line
}
// Search for a user based on their course_name.
if ($request->has('location_name')) {
$institute->whereHas('locations', function ($query) use ($request) {
$query->where('locations.location_name', $request->input('location_name'));
})
->with('locations'); // <<<<<<< add this line
}
这也将获取相关的课程和位置。