gpt4 book ai didi

php - Laravel 中的查询

转载 作者:行者123 更新时间:2023-11-29 21:51:38 25 4
gpt4 key购买 nike

问题

你好!我需要进行查询,在其中响应具有 list_id = id 的所有任务,并且还需要响应具有 task_id = taskID 的所有子任务。但我不知道如何对 taskID 进行正确的查询..

我的代码

$response['lists'] = Lists::findorfail($id);
$response['tasks'] = Tasks::latest()->where('list_id','=',$id)->get();

上层代码工作正常,我通过列表id获取所有任务。

$taskID = Tasks::latest()->where('list_id','=',$id)->get('id');

$response['subtasks'] = Subtasks::latest()->where('task_id','=',$taskID)->get();

目前我有这个查询,但它不起作用,我只是展示它以更好地解释我想要做什么。

There is image to see what I meant, how it must look like, when work properly

在该图像中,您可以看到,我的列表中有 2 个任务(我使用上面的代码获取它),在该弹出表单上您可以看到第一个任务有 2 个子任务(与第二个任务相同),所以我想要进行查询以输出每个任务的正确子任务。

$response['subtasks'] = Subtasks::latest()->where('task_id','=',4)->get();

我使用这个不正确的代码,只是为了展示示例。 'task_id','=',4 这意味着我获得了 id = 4 任务的所有子任务。但现在每个任务都有这些子任务。所以我需要查询来自动获取任务ID并正确输出。

我希望你明白我想要得到什么。

关系结构

There you can see relationships of tables. There you can see output after adding code from answer.

最佳答案

这行代码:

$taskID = Tasks::latest()->where('list_id','=',$id)->get('id');

将返回一个集合,其中元素是带有 list_id = $id 的任务

所以你不能在查询中使用 $taskID 作为 ID 号,例如:

$response['subtasks'] = Subtasks::latest()->where('task_id','=',$taskID)->get();

相反,你可以这样做:

// this will return an array of taskID
$taskIDs = $response['tasks']->pluck('task_id');

// then you can do it like
foreach ($taskIDs as $taskID) {
$response['subtasks'][$taskID] = Subtasks::latest()->where('task_id','=',$taskID)->get();
}

更新:您也可以这样使用:

//This will return a collection of all subtasks    
$subtasks = Subtasks::latest()->get();

//This will turn subtasks in to group according to tasks_id
$response['subtasks'] = $subtasks->groupBy('task_id');

所有与 Laravel Collection 相关的方法都可以引用 here

问候,

关于php - Laravel 中的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33582822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com