如何使用资源返回laravel 5.5 api中的选择

问题描述 投票:0回答:3

我想在用户指定id时从我的数据库中返回一个选择。

我有一个laravel 5.5 API,在api.php中有以下路由。

Route::get('companytasks/{id}','TaskController@showOfCompany');

在我的TaskController中,我有以下功能:

public function showOfCompany($id)
{
    // Get tasks with the specifiec company id
    $companytasks = Task::findOrFail($id);
    // Return single task as a resource
    return new TaskResource($companytasks);
}

我的资源看起来像这样:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Task extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'TaskCompanyId' => $this->TaskCompanyId,
            'TaskName' => $this->TaskName,
            'TaskDescription' => $this->TaskDescription,
            'Branche' => $this->Branche,
            'Budget' => $this->Budget,
            'TaskFinishDate' => $this->TaskFinishDate,
            'PaydFor' => $this->PaydFor,
            'PublicTask' => $this->PublicTask,
            'created_at' => $this->created_at
        ];
    }
}

我想从数据库中选择'TaskCompanyId'等于$ id。

我可以使用控制器中的以下行执行此操作:

$companytasks = Task::where('TaskCompanyId','=',$id)->get();

但这对我不起作用,但我可以添加 - > first(),因此它只返回第一个出现但我想要返回所有的ocurrances。我该如何实现这一目标?

php laravel api
3个回答
0
投票

您在where子句中使用'CompanyTaskId'而不是'TaskCompanyId'


0
投票

看起来不错,但试试这个。

$companytasks =  App\Task::where( 'TaskCompanyId' , $id )->get();

如果你想要,你可以订购或分页

$companytasks =  App\Task::where( 'TaskCompanyId' , $id )
     ->orderBy('CompanyTaskId', 'desc')
     ->paginate(15);

0
投票

我设法通过将资源代码更改为:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\Json\ResourceCollection;

class Task extends ResourceCollection
{
    public function toArray($request)
    {
        return [
            'data' => $this->collection
        ];
    }
}

进行选择会返回集合而不是对象,因此需要ResourceCollection而不是JsonResource。

© www.soinside.com 2019 - 2024. All rights reserved.