我有五个表:请求者、文档类型、协议(protocol)、流程和文档.
关系
- 请求者有多种文档类型。
- 请求者有许多协议(protocol)。
- 协议(protocol)有许多流。
- Flow 有许多文档。
- 文档类型有许多文档。
问题
选择具有第一个流(假设序列= 1)的所有协议(protocol)以及具有所有文档类型的文档 em> 协议(protocol)请求者。
换句话说,选择没有悬而未决的协议(protocol),这意味着第一个流内的文档具有协议(protocol)请求者所需的所有文档类型。
解决方案
我最终得到了一个实际上不起作用的解决方案,因为我无法访问协议(protocol)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
闭包中的模型值,或者是否存在另一种替代方法来帮助我解决此查询?
最佳答案
试试这个:
$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();
关于php - Laravel - 在查询生成器中访问模型值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52388136/