請問在讀取文章時要一同返回發佈這篇文章的作者資料,出現了附圖的錯誤,不知有邦友遇過此類的問題嗎?
Error
UserResource
public function toArray($request)
{
return [
'name' => $this->name,
'email' => $this->email
];
}
PostResource
public function toArray($request)
{
return [
'userid' => UserResource::collection($this->userid),
'title' => $this->title,
'content' => $this->content,
'created_at' => $this->created_at->toDateTimeString(),
'updated_at' => $this->updated_at->toDateTimeString()
];
}
PostController
use App\Models\Post;
use App\Http\Resources\PostResource;
public function index()
{
$records=Post::all();
return PostResource::collection($records);
}
UserModel
public function post(){
return $this->hasMany(Post::class,'userid');
}
PostModel
public function user(){
return $this->belongsTo(User::class,'userid');
}
routes\api.php
use App\Http\Controllers\PostController;
Route::get('post',[PostController::class,'index']);
先說那個first()錯誤
那是因為UserResource::collection()接受的參數是集合類型
你的$this->userid應該是int/字串被當集合處理自然就會產生錯誤
正解的部分
應該是用不到UserResource
直接用 $this->user->userid
或是你的Post本來就有的userid欄位 $this->userid
PostResource
public function toArray($request)
{
return [
'userid' => $this->user->userid,
'title' => $this->title,
'content' => $this->content,
'created_at' => $this->created_at->toDateTimeString(),
'updated_at' => $this->updated_at->toDateTimeString()
];
}
如果用UserResource的話
我會這樣用
new UserResource($this->user->toArray()),
例PostResource
public function toArray($request)
{
return [
'author' => new UserResource($this->user->toArray()),
'title' => $this->title,
'content' => $this->content,
'created_at' => $this->created_at->toDateTimeString(),
'updated_at' => $this->updated_at->toDateTimeString()
];
}
UserResource
public function toArray($request)
{
return [
'data' => $this->collection,
];
}