如何解决API资源为空
在我编写的API项目中,我有2个表中的数据,“跟随者”和“跟随者”。我想使用Resource对其进行自定义并将其导出为json,但是用户信息为空。您认为是什么原因?
FollowerResource
public function toArray($request)
{
return [
'id' => $this->id,'user' => new UserResource($this->user),];
}
关注资源
public function toArray($request)
{
return [
'id' => $this->id,];
}
UserController
public function followUser() {
$follows = Follows::all();
return response()->json(FollowResource::collection($follows),200);
}
public function followerUser() {
$followers = Followers::all();
return response()->json(FollowerResource::collection($followers),200);
}
输出
关注者和关注者路线
{
"id": 1,"user": null
},{
"id": 2,{
"id": 3,{
"id": 4,{
"id": 5,{
"id": 6,"user": null
}
在此先感谢您的帮助。祝您身体健康。
更新
用户资源
public function toArray($request)
{
return [
'user_id' => $this->id,'email' => $this->email,'description' => $this->description,'first_name' => $this->first_name,'last_name' => $this->last_name,'full_name' => $this->first_name . ' ' . $this->last_name,];
}
更新两个
关注者数据
Illuminate\Database\Eloquent\Collection {#1240 ▼
#items: array:11 [▼
0 => App\Models\Followers {#1241 ▼
#connection: "mysql"
#table: "followers"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:4 [▼
"id" => 1
"user_id" => 3
"created_at" => "2002-08-01 03:26:41"
"updated_at" => "2020-08-13 11:32:28"
]
#original: array:4 [▶]
#changes: []
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
1 => App\Models\Followers {#1242 ▶}
2 => App\Models\Followers {#1243 ▶}
3 => App\Models\Followers {#1244 ▶}
4 => App\Models\Followers {#1245 ▶}
5 => App\Models\Followers {#1246 ▶}
6 => App\Models\Followers {#1247 ▶}
7 => App\Models\Followers {#1248 ▶}
8 => App\Models\Followers {#1249 ▶}
9 => App\Models\Followers {#1250 ▶}
10 => App\Models\Followers {#1251 ▶}
]
}
解决方法
将您的关注资源更改为此
public function toArray($request)
{
return [
'id' => $this->id,'user' => new UserResource($this->user_id),];
}
在“关注资源”文件中,添加以下行
public function toArray($request)
{
$user = User::find($this->user_id);
return [
'id' => $this->id,'user' => new UserResource($user),];
}
让我知道是否有帮助
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。