1 回答
TA贡献1866条经验 获得超5个赞
您获得client和search未正确分组时的条件
Contact::when($request->client && $request->search, function ($q) use($request) {
$q->whereHas('companies', function ($q) use ($request) {
$q->where('is_client', true);
})->where(function ($q) use ($request) {
$q->where('first_name', 'like', '%'.$request->search.'%')
->orWhere('last_name', 'like', '%'.$request->search.'%')
->orWhereHas('companies', function ($q) use ($request) {
$q->where('name', 'like', '%' . $request->search . '%');
});
});
})->when($request->client == null && $request->search, function ($q) use($request) {
$q->where('first_name', 'like', '%'.$request->search.'%')
->orWhere('last_name', 'like', '%'.$request->search.'%')
->orWhereHas('companies', function ($q) use ($request) {
$q->where('name', 'like', '%' . $request->search . '%');
});
})->when($request->client && $request->search == null, function ($q) use ($request) {
$q->whereHas('companies', function ($q) use ($request) {
$q->where('is_client', true);
});
})
->paginate(30)
条件is_client必须与条件分开search
您应该已经注意到,您可以轻松地在此处缩小代码
$contactQuery = Contact::query();
if ($request->client) {
$contactQuery->whereHas('companies', function ($q) {
$q->where('is_client', true);
});
}
if ($request->search) {
$contactQuery->where(function ($q) use ($request) {
$q->where('first_name', 'like', '%'.$request->search.'%')
->orWhere('last_name', 'like', '%'.$request->search.'%')
->orWhereHas('companies', function ($q) use ($request) {
$q->where('name', 'like', '%' . $request->search . '%');
});
});
}
$contacts = $contactQuery->paginate(30);
- 1 回答
- 0 关注
- 199 浏览
添加回答
举报