【问题标题】:Laravel Fractal ManagerLaravel 分形管理器
【发布时间】:2015-11-27 21:23:37
【问题描述】:

我编写了一个转换器类,用于在 API 中输出数据:

APPTRANSFORMER:

<?php
namespace App\Transformer;

use App\Classes\AED;
use League\Fractal\TransformerAbstract;

class AEDTransformer extends TransformerAbstract {
    public function transform(AED $aed) {
        return [
            'owner' => $aed->owner,
            'street' => $aed->street,
            'latitude' => $aed->latitude,
            'longitude' => $aed->longitude,
            'annotationType' => $aed->annotation_type
        ];
    }
}

以及获取请求数据的控制器方法:

控制器:

// Show specific AED
public function show($id) {
    // Find AED by ID
    $aed = AED::find($id);
    $rawData = $this->respondWithItem($aed, new AEDTransformer);
    $meta = ['meta' => 'TestMeta'];
    $data = array_merge($rawData, $meta);

    if (!$aed) {
        return $this->respondNotFound("AED existiert nicht.");
    }

    return $data;
}

当我调用 URL 时出现错误:

AEDTransformer.php 第 16 行中的 ErrorException:参数 1 传递给 App\Transformer\AEDTransformer::transform() 必须是 App\Classes\AED,给定 null,调用 /home/vagrant/Projects/MFServer/vendor/league/fractal/src/Scope.php 第 307 行并定义

AED 等级:

<?php
namespace App\Classes;

use Illuminate\Database\Eloquent\Model;

class AED extends Model {

    protected $table = 'aeds';
    protected $fillable = ['owner', 'street', 'postal_code', 'locality', 'latitude', 'longitude', 'annotation_type'];
    public $timestamps = true;

    public $id;
    public $owner;
    public $object;
    public $street;
    public $postalCode;
    public $locality;
    public $latitude;
    public $longitude;
    public $annotation_type;
    public $distance;

    public function set($data) {
        foreach ($data as $key => $value) {
            $this->{$key} = $value;
        }
    }
}

我认为它一定与 AED 类中的“扩展模型”有关,但我不明白原因。它只是一个扩展。还是我看错了地方,理解错了信息?

【问题讨论】:

  • 在您的控制器中调用$this-&gt;respondsWithItem 之前,您确定可以找到模型吗?在调用之前var_dump($aed); 的输出是什么?
  • 您好,我也有同样的问题。当您的表中不存在记录时,$aed = AED::find($id); 返回 null 时会发生这种情况。要确认这一点,请$aed = AED::find($id); dd($aed);

标签: php laravel-5


【解决方案1】:

您收到此错误是因为 $aed = AED::find($id); 正在返回 null,这意味着该记录不存在。

你可以这样做

public function show($id) {

   // Find AED by ID

    $aed = AED::find($id);

    if (!$aed) { //just to be sure
       return $this->respondNotFound("AED existiert nicht.");
    }


    $rawData = $this->respondWithItem($aed, new AEDTransformer);
    $meta = ['meta' => 'TestMeta'];
    $data = array_merge($rawData, $meta);

    return $data;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2018-02-07
    相关资源
    最近更新 更多