我将Laravel与Resources结合使用来创建REST Api。我想获得一个包含有关关系元素的信息的json,例如示例
{
"id": 30,
"calf": 23,
"chest": 27
"user_id": {
"id": 30,
"email": "test@example.com"
}}
但是当我在docs中创建代码时,出现错误“在int上调用成员函数first()”。有人可以告诉我我做错了什么吗?我做了完全一样的事情,就像在文档中一样,我也尝试使用whenLoaded,但是出现了同样的错误。这是我的代码:
class CircuitMeasurementResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $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);
}
}
答案 0 :(得分:0)
您的代码中有些错误:
CircuitMeasurement
中,更改为:// since it gets just one
public function user(){
return $this->belongsTo(User::class);
}
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
];
}
答案 1 :(得分:0)
您根本不需要使用UserResource,只需通过该ID查找用户
public function toArray($request)
{
return [
'id' => $this->id,
'calf' => $this->calf,
'chest' => $this->chest,
'user_id' => User::find($this->user_id),
];
}
{
"data": {
"id": 30,
"calf": 23,
"chest": 27,
"user_id": {
"id": 30,
"name": "Charity Douglas",
"email": "demmerich@example.org",
"email_verified_at": "2019-11-06 11:25:07",
"created_at": "2019-11-06 11:25:07",
"updated_at": "2019-11-06 11:25:07"
}
}
}
希望这会有所帮助