php - Laravel - 在查询生成器中访问模型值

标签 php mysql laravel eloquent

我有五个表:请求者文档类型协议(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/

相关文章:

php - 如何将 boolean 参数传递给 php 函数?

php - 注意第31行的: Use of undefined constant DB_HOST - assumed 'DB_HOST' in C:\xampp\htdocs\blog\system\functions. php

php - 使用 AJAX、PHP 和 JSON 从 MySQL 数据库获取数据项

php - $wpdb->insert 没有重新分配唯一字段

php - 如何在 Laravel 5 中添加外部类

php - 不显示多个 SELECT 变量

php从一张或多张表中获取数据

mysql - 连接多对多并将许多引用合并到单行中

php - 无法通过 Laravel SQLSTATE [08006] [7] FATAL 连接到 PgSQL

php - Apache 在测试服务器上设置多个项目