如何使用with语句将筛选器应用于关系表



我写了一段代码来过滤关系数据,但没有得到好的结果。这是代码。父查询和具有查询的查询是独立工作的。

public function get(Request $request, Company $company, Survey $survey)
{
$this->authorize('update', $survey->company);
$search = $request->get('search');
$query = EsAnswer::where(['company_id' => $company->id, 'survey_id' => $survey->id])
->orderByDesc('created_at')
->with(['employee'=> function ($q) use($search) {
$q->where('first_name', 'LIKE', "%{$search}%");
$q->orwhere('last_name', 'LIKE', "%{$search}%");
$q->select('id', 'first_name', 'last_name');   
}]);
if ($request->has('start_date')) {
$query->whereDate('created_at', '>=', $request->start_date);
}
if ($request->has('end_date')) {
$query->whereDate('created_at', '<=', $request->end_date);
}
$answers = $query->get()->groupBy('submission_id');
// ->paginate('100');
return $answers;
}

当我使用这个时

{
"search":""
}

我收到的回复是:

{
"id": 2,
"company_id": 1,
"employee_id": 1,
"survey_id": 2,
"es_question_id": 1,
"answer": "done",
"submission_id": "1",
"mark_as_read": 1,
"created_at": "2020-08-19 12:18:25",
"updated_at": "2020-08-26 06:55:21",
"employee": {
"id": 1,
"first_name": "Baseapp",
"last_name": "saw"
}
}

当我试图按另一个表中的员工姓名进行搜索时,如果数据存在,则应过滤数据并给出响应,但如果员工姓名或搜索数据不存在,则数据不应给出任何响应。如何处理?

{
"search":"sure"
}

{
"id": 2,
"company_id": 1,
"employee_id": 1,
"survey_id": 2,
"es_question_id": 1,
"answer": "done",
"submission_id": "1",
"mark_as_read": 1,
"created_at": "2020-08-19 12:18:25",
"updated_at": "2020-08-26 06:55:21",
"employee": null
}

这里的数据为空,但为什么显示父数据。请帮助并给出另一个使用关系数据进行过滤的想法。

我们使用whereHas在相关表中进行过滤。所以像一样使用它

$query = EsAnswer::with('employee:id,first_name,last_name')
->where(['company_id' => $company->id, 'survey_id' => $survey->id])
->whereHas('employee', function($query) use($search) {
$query->where('first_name', 'LIKE', "%{$search}%")
->orwhere('last_name', 'LIKE', "%{$search}%");
})
->orderByDesc('created_at');

这将在您的相关表中搜索,如果没有找到任何内容,则返回null。我为急切地加载数据添加了一种优雅的方式。你也应该看看这个。

它使用whereHas,然后使用With:

$query = EsAnswer::where(['company_id' => $company->id, 'survey_id' => $survey->id])
->orderByDesc('created_at')
->whereHas('employee', function ($q) use($search) {
return $q->where('first_name', 'LIKE', "%{$search}%")
->orwhere('last_name', 'LIKE', "%{$search}%");   
})->with(['employee' => function ($q){
$q->select('id', 'first_name', 'last_name');
}]);

使用whereHas()函数

$query = EsAnswer::with('employee:id,first_name,last_name')
->where(['company_id' => $company->id, 'survey_id' => $survey->id])
->whereHas('employee', function($query) use($search) {
$query->where('first_name', 'LIKE', "%$search%")
->orwhere('last_name', 'LIKE', "%$search%");
})
->orderByDesc('created_at');

ref链接https://laravel.com/docs/7.x/eloquent-relationships#querying-关系存在

相关内容

  • 没有找到相关文章

最新更新