Lumen + Doctrine findAll returns 空对象数组

Lumen + Doctrine findAll returns array of empty objects

我已经用 Doctrine 设置了 Lumen (laravel-doctrine/orm)

当我尝试在 HTTP 路由上获取结果(即 $this->em->getRepository(Student::class)->findAll();)时,我得到一个空卷曲数组括号。

如何正确地进行序列化运行?

首先,您需要用 Illuminate\Support\Collection class 包裹您的结果,例如:

use  Illuminate\Support\Collection;

return Collection::make(
    $this->em->getRepository(Student::class)->findAll()
);

之后,修改您的 Student class,将其分配给 Illuminate\Contracts\Support\Arrayable 合同。

use Illuminate\Contracts\Support\Arrayable;

class Student implements Arrayable
{
    // Your code here
}

接下来,您应该对 Student class 实施 toArray 方法:

use Illuminate\Contracts\Support\Arrayable;

class Student implements Arrayable
{
    public function toArray()
    {
        return [
            'id' => $this->getId(),
            // ... and so on ...
        ];
    }
}