就我而言,我必须按城市或学院过滤数据
我有两张表,如下面
Institutes table
id | institute_name | phoneNumber
-------------------------------------
1 infocampus 9999999999
-------------------------------------
2 jspider 2348234982
courses table
id | institute_id | course_name
------------------------------------------
1 1 java
2 1 php
我创建的关系
Institue model
public function courses()
{
return $this->hasMany(Course::class);
}
Course model
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'));
});
}
return response()->json($institute->get());
}
从上面我可以过滤数据,但它只显示机构表数据,如下所示
[
{
"id": 2,
"institute_name": "qspider",
"institute_contact_number": "9903456789",
"institute_email": "qspider@gmail.com",
"status": "1",
"created_at": null,
"updated_at": null
}
]
但我需要的是当我使用course_name或instute_name进行搜索时,我需要从institue表中获取数据以及课程表数据。 有人可以帮忙吗?
答案 0 :(得分:0)
尝试以下方法,应该将研究所带回课程。
$institute->with(['courses' => function ($query) use ($request) {
$query->where('courses.course_name', $request->input('course_name'));
}])