无法在 json Laravel 中返回关系元素



Im使用Laravel和Resources创建REST-Api。我想得到一个json,其中包含关于关系元素的信息,比如示例

{
"id": 30,
"calf": 23,
"chest": 27
"user_id": {
"id": 30,
"email": "test@example.com"
}}

但当我像在文档中那样创建代码时,我得到了一个错误"在int上调用成员函数first(("。有人能告诉我我做错了什么吗?我做了完全相同的事情,就像在文档中一样,我也尝试使用whenLoaded,但出现了同样的错误。这是我的代码:

class CircuitMeasurementResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param  IlluminateHttpRequest  $request
* @return array
*/
public function toArray($request)
{
//        return parent::toArray($request);
return [
'id' => $this->id,
'calf' => $this->calf,
'chest' => $this->chest,
'user_id' => UserResource::collection($this->user_id)
];
}
}

我的方法显示在控制器:

public function show(CircuitMeasurement $circuitMeasurement): CircuitMeasurementResource {
return new CircuitMeasurementResource($circuitMeasurement);
}

我的型号:

class CircuitMeasurement extends Model
{
protected $fillable = [
'user_id', 'calf', 'thigh', 'hips', 'waist', 'chest', 'neck', 'biceps'
];
public function users(){
return $this->belongsTo(User::class);
}
}
class User extends Authenticatable
{
use Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function weightMeasurement(){
return $this->hasMany(WeightMeasurement::class);
}
public function circuitMeasurement(){
return $this->hasMany(CircuitMeasurement::class);
}
}

您的代码中有一些错误:

  1. CircuitMeasurement中,更改为:
// since it gets just one
public function user(){
return $this->belongsTo(User::class);
}
  1. 您将ResourceName::collection()用于多个项目,将new ResourceName()用于单个项目。将资源更改为:
public function toArray($request)
{
//        return parent::toArray($request);
return [
'id' => $this->id,
'calf' => $this->calf,
'chest' => $this->chest,
'user_id' => new UserResource($this->user)
//I think you should name user instead of user_id
];
}

最新更新