【发布时间】:2018-08-08 10:36:08
【问题描述】:
每当用户指定 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() 添加到它,因此它只返回第一次出现,但我希望返回所有出现。我如何做到这一点?
【问题讨论】:
-
如果我在不使用资源的情况下返回 $companytasks,它可以完美运行。我只需要资源来指定 bing 返回的字段和不返回的字段。如何使用我的资源进行这项工作?