【问题标题】:Can't return relationship element in json Laravel无法在 json Laravel 中返​​回关系元素
【发布时间】:2020-03-02 20:37:46
【问题描述】:

我使用 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  \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)
        ];
    }
}

我的方法在Controller中显示:

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);
    }

}

【问题讨论】:

    标签: json laravel api eloquent


    【解决方案1】:

    您的代码中有几处有问题:

    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
            ];
        }
    

    【讨论】:

      【解决方案2】:

      您根本不需要使用 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"
              }
          }
      }
      

      希望对你有帮助

      【讨论】:

      • 嗨!感谢您的回答,效果很好,但我不能将此标记为第二个接受的答案。对不起:(
      • 没关系,随便用吧
      猜你喜欢
      • 2017-11-23
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 2014-08-21
      • 2016-06-21
      相关资源
      最近更新 更多