我有五个表:请求者,文档类型,协议,流程和文档< / em>。
关系
问题
选择所有具有第一个流程(假设序列= 1)的协议,其中 documents 具有所有文档类型协议 requester 的em>。
换句话说,选择没有待处理的协议,这意味着在第一个流中包含文档的协议具有协议请求者所需的所有文档类型。
解决方案
最后我得到了一个实际上不起作用的解决方案,因为我无法访问协议whereHas
内部的 requester_id 值:
// All document types id's group by requester id's.
$documentTypesByRequester = DocumentType::all()
->groupBy('requester_id')
->map(function ($documentTypes, $requesterId) {
return $documentTypes->pluck('id')
->toArray();
})->toArray();
// Defined statically to reduce the complexity of question.
// $documentTypesByRequester = [
// 1 => [1, 2, 3],
// 2 => [4, 5]
// ];
// Here I have to select all protocols that have flows with
// documents having all document types of protocol requester.
$protocols = Protocol::whereHas('flows', function ($flows) use ($documentTypesByRequester) {
//
// *---------------------------------------
// * THIS DOESN'T WORK BUT IS WHAT I NEED!
// *---------------------------------------
//
// Access the requester id for current protocol.
$requesterId = $flows->first()
->protocol
->requester_id;
$documentTypesId = $documentTypesByRequester[$requesterId];
return $flows->where('sequence', 1)
->whereHas('documents', function ($documents) use ($documentTypesId) {
return $documents->whereIn('document_type_id', $documentTypesId);
}, '=', count($documentTypesId));
})->get();
在whereHas
闭包内部有某种方法可以访问模型的值,或者存在另一种方法可以帮助我解决此查询?
答案 0 :(得分:1)
尝试一下:
$documentTypes = DocumentType::whereColumn('requester_id', 'protocol.requester_id');
$protocols = Protocol::whereHas('flows', function ($query) use ($documentTypes) {
$query->where('sequence', 1)
->whereHas('documents', function ($query) use ($documentTypes) {
$query->select(DB::raw('count(distinct document_type_id)'))
->whereIn('document_type_id', (clone $documentTypes)->select('id'));
}, '=', DB::raw('('.(clone $documentTypes)->selectRaw('count(*)')->toSql().')'));
})->get();