Мне нужно было вернуть этот json, я использую ресурсы API в Laravel:
{
"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
];
}
}
Пользовательский ресурс.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),
]
];
}
}
Модели/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» в массиве
Что я могу сделать? Спасибо.
да, теперь я получаю эту ошибку: Неопределенный ключ массива "id"
Может быть, потому что здесь: new ProjectCollection($this->collection->map->only(['firstProject']) мне нужно передать красноречивую коллекцию?
Я смог решить эту проблему следующим образом:
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)
{
$collection1 = $this->collection->map->only(['firstProject']);
$collection2 = $collection1->map(function($item, $key) {
return $item['firstProject'];
});
return [
'included' => $collection2
];
}
}
Теперь у меня отсутствует еще одна проблема, но я отправлю еще один вопрос, спасибо
вы пробовали вместо
$this->id
использовать$this['id']
?