【问题标题】:Laravel - How to access attribute in whereHas clause?Laravel - 如何访问 whereHas 子句中的属性?
【发布时间】:2019-02-21 21:01:15
【问题描述】:

我的实体是这样的:

  • 请求者类型
  • 协议
  • 文档
  • 文档类型

关系是这样的:

  • 协议属于请求者类型。
  • 协议有很多流程。
  • Flow 包含许多文档。
  • 文档属于文档类型。
  • 文档类型属于请求者类型。

我需要的查询:

选择所有 Protocols 在第一个 Flow(假设序列 = 1)中具有 Documents 的所有必需 Document他的 Requester Type 的类型(实际上存储在 Protocol 中)。

例如,假设我有请求者类型为 1 的协议,并且想要检查所有文档类型是否都存在于它们的第一流文档中。要了解所有必需的文档类型,只需从协议请求者类型中查询即可。

我开始:

$documentsTypesByRequester = DocumentType::groupBy('requester_id')
    ->get();

$protocols = Protocol::whereHas('flows', function ($flows) use ($documentsTypesByRequester) {
    return $flows->where('sequence', 1)
        ->whereHas('documents', function ($documents) use ($documentsTypesByRequester) {
            // Select all documents that has the same
            // requester id of protocol and all document types
            // are present...
            $requesterId = // How to access protocol requester id?
            $documentTypes = $documentsTypesByRequester[$requesterId];
            // ...
        });
});

我需要用 Eloquent 而不是 Collection 来解决这个问题。

【问题讨论】:

    标签: php database laravel eloquent


    【解决方案1】:

    似乎您正试图从->whereHas() 中获得双重职责,我认为这只是将您的flows 限制为具有documents 的人的限制。尝试从封装所有匹配逻辑的 ->where() 调用开始,然后使用简单的 ->whereHas('documents') 并看看它是如何工作的。

    所以是这样的:

    $documentsTypesByRequester = DocumentType::groupBy('requester_id')
    ->get();
    
    $protocols = Protocol::whereHas('flows', function ($flows) use ($documentsTypesByRequester) {
        return $flows->where('sequence', 1)
            ->where('documents', function ($query) use ($documentsTypesByRequester) {
                // Put all of your logic for choosing a document here
                // ...
            })
        ->whereHas('documents');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-07
      • 2019-11-17
      • 2020-04-14
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多