我被要求返回这个json,我正在使用Laravel中的api资源:
{
"data": [
{
"type": "users",
"id": "1",
"attributes": {
"name": "test name",
"lastname": "test lastname"
"projects": 2
},
"relationships": {
"projects": {
"data": [
{
"id": 1,
"type": "projects"
}
]
}
}
}
],
"included": [
{
"type": "projects",
"id": 1,
"attributes": {
"title" : "Test",
"description": "Test",
....
....
}
}
]
}
一个用户有许多项目,我是这样做的:
ProjectCollection.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class ProjectCollection extends ResourceCollection
{
public function toArray($request)
{
return [
'data' => $this->collection
];
}
}
ProjectResource.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class ProjectResource extends JsonResource
{
public function toArray($request)
{
return [
"type" => "projects",
"id" => $this->id,
"attributes" => [
"title" => $this->title,
"description" => $this->description,
....
....
]
];
}
}
UserCollection.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class UserCollection extends ResourceCollection
{
public function toArray($request)
{
return [
'data' => $this->collection
];
}
public function with($request)
{
return [
//'included' => ProjectResource::collection($this->collection->map->only(['firstProject']) it doesn't work
'included' => new ProjectCollection($this->collection->map->only(['firstProject']) // it doesn't work
];
}
}
UserResource.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
public function toArray($request)
{
return [
"type" => "users",
"id" => $this->id,
"attributes" => [
"name" => $this->name,
"lastname" => $this->lastname
"projects" => $this->whenCounted('projects')
],
"relationships" => [
"projects" => new ProjectCollection($this->firstProject),
]
];
}
}
Models/User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class User extends Model
{
use HasFactory;
protected $guarded = ['id'];
public function projects()
{
return $this->hasMany(Project::class);
}
public function firstProject()
{
return $this->projects()->oldest()->limit(1);
}
}
UsersController.php
$users = User::withCount('projects')->latest()->get();
return new UserCollection($users);
我收到此错误:
PHP 8.1.1 9.39.0试图读取数组中的属性“id”
我能做什么?谢谢。
1条答案
按热度按时间ia2d9nvy1#
我可以这样解决这个问题:
UserCollection.php
现在我有另一个问题失踪,但我会张贴另一个问题,谢谢