为什么Laravel中的Eloquent Collection对象可以被json_encode

陈渊
2023-12-01

我们知道,在laravel框架中使用 Eloquent 模型来查询数据库返回的是 Collection对象,但是我们却可以调用 json_encode 来将其内容转换成 json 串,要知道普通的对象是没法做到这一点的。

相关的文件

Illuminate\Database\Eloquent\Collection.php
Illuminate\Support\Collection.php

根本原理是该类实现了 json模块 的JsonSerializable接口的 jsonSerialize 方法。
PHP文档 https://www.php.net/manual/zh/class.jsonserializable.php

Illuminate\Support\Collection 类的定义:

class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate, Jsonable, JsonSerializable
{
	public function jsonSerialize()
    {
        return array_map(function ($value) {
            if ($value instanceof JsonSerializable) {
                return $value->jsonSerialize();
            } elseif ($value instanceof Jsonable) {
                return json_decode($value->toJson(), true);
            } elseif ($value instanceof Arrayable) {
                return $value->toArray();
            }

            return $value;
        }, $this->items);
    }
    ....
}
 类似资料: