【问题标题】:How do I make a query() where the result requires another query()?如何在结果需要另一个查询()的情况下进行查询()?
【发布时间】:2019-09-29 00:41:51
【问题描述】:

我目前正在使用 Laravel Excel 来构建工作表。工作表需要一个返回集合的查询,我需要该集合的结果来查询 whereBetween() 以获取 map() 的集合。

我确实有能力收集所有提交,但我需要从用户的模型中严格指定,以便关系正常工作并且仅限于分配给该用户的内容。

我在另一个代码区域使用的当前方法使用以下方法:

$user_contracts = \Auth::user()->contracts()->get();
$submission_id = array();
foreach ($user_contracts as $contract) {
    $submissions = $contract->submissions()->get();
    foreach ($submissions as $submission) {
        $submission_id[] = $submission->id;
    }
}

$user_submissions = FormSubmission::whereIn('id', $submission_id)->get();

返回正确的结果。

我相信我需要使用这个 query() 函数来生成 Laravel Excel 生成工作表所需的 map() 函数。

    public function query()
    {
        $time_start = Carbon::now()->setTime(0, 0, 0);
        $time_end = Carbon::now()->setTime(24, 0, 0);
        return User::query()->find($this->user->id)->contracts()->submissions()->whereBetween('created_at', [$time_start, $time_end]);
    }

错误结果:Property [submissions] does not exist on this collection instance.

【问题讨论】:

    标签: laravel laravel-5.8


    【解决方案1】:

    感谢Laravel Eloquent nested query 我能够回答我自己的问题,有点。

    这是我最终得到的代码。

        public function query()
        {
            $time_start = Carbon::now()->setTime(0, 0, 0);
            $time_end = Carbon::now()->setTime(24, 0, 0);
            $contracts = $this->user->contracts()->get()->pluck('id')->toArray();
    
            return FormSubmission::query()->whereHas('contracts', function($q) use ($contracts) {
                $q->whereIn('contract_id', $contracts);
            })->whereBetween('created_at', [$time_start, $time_end]);
        }
    

    我仍然愿意接受更优雅的答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2023-02-07
      相关资源
      最近更新 更多