[ Laravel 5.7 文档 ] Eloquent ORM —— 序列化

栏目: PHP · 发布时间: 6年前

内容简介:当构建 JSON API 时,经常需要转化模型和关联关系为数组或 JSON。Eloquent 提供了便捷方法以便实现这些转换,以及控制哪些属性被包含到序列化中。要转化模型及其加载的关联关系为数组,可以使用还可以转化整个模型集合为数组:

简介

当构建 JSON API 时,经常需要转化模型和关联关系为数组或 JSON。Eloquent 提供了便捷方法以便实现这些转换,以及控制哪些属性被包含到序列化中。

序列化模型 & 集合

序列化为数组

要转化模型及其加载的关联关系为数组,可以使用 toArray 方法。这个方法是递归的,所以所有属性及其关联对象属性(包括关联的关联)都会被转化为数组:

$user = App\User::with('roles')->first();
return $user->toArray();

还可以转化整个模型集合为数组:

$users = App\User::all();
return $users->toArray();

序列化为 JSON

要转化模型为 JSON,可以使用 toJson 方法,和 toArray 一样, toJson 方法也是递归的,所有属性及其关联属性都会被转化为 JSON。还可以指定 PHP 支持的 JSON 编码选项

$user = App\User::find(1);
return $user->toJson();
return $user->toJson(JSON_PRETTY_PRINT);

你还可以转化模型或集合为字符串,这将会自动调用 toJson 方法:

$user = App\User::find(1);
return (string) $user;

由于模型和集合在转化为字符串的时候会被转化为 JSON,你可以从应用的路由或控制器中直接返回 Eloquent 对象:

Route::get('users',function(){
    return App\User::all();
});

在 JSON 中隐藏属性

有时候你希望在模型数组或 JSON 显示中隐藏某些属性,比如密码,要实现这个功能,在定义模型的时候设置 $hidden 属性:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * 在数组中隐藏的属性
     *
     * @var array
     */
    protected $hidden = ['password'];
}

注:如果要隐藏关联关系,使用关联关系的方法名,而不是动态属性名。

此外,可以使用 $visible 属性来定义模型数组和 JSON 显示的属性白名单:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * 在数组中显示的属性
     *
     * @var array
     */
    protected $visible = ['first_name', 'last_name'];
}

临时暴露隐藏属性

如果你想要在特定模型中临时显示隐藏的属性,可以使用 makeVisible 方法,该方法以方法链的调用方式返回模型实例:

return $user->makeVisible('attribute')->toArray();

类似的,如果你想要隐藏给定模型实例上某些显示的属性,可以使用 makeHidden 方法:

return $user->makeHidden('attribute')->toArray();

追加值到 JSON

有时候,需要添加数据库中没有的字段到数组中,要实现这个功能,首先要为这个值定义一个访问器:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * 为用户获取管理员标识
     *
     * @return bool
     */
    public function getIsAdminAttribute()
    {
        return $this->attributes['admin'] == 'yes';
    }
}

定义好访问器后,添加字段名到该模型的 appends 属性。需要注意的是,尽管访问器使用“camel case”形式定义,属性名通常以“snake case”的方式被引用:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * 追加到模型数组表单的访问器
     *
     * @var array
     */
    protected $appends = ['is_admin'];
}

字段被添加到 appends 列表之后,将会被包含到模型数组和 JSON 中, appends 数组中的属性还会遵循模型中配置的 visiblehidden 设置。

运行时追加

你可以在单个模型上使用 append 方法来追加属性,或者,你可以使用 setAppends 方法为给定模型覆盖整个追加属性数组:

return $user->append('is_admin')->toArray();

return $user->setAppends(['is_admin'])->toArray();

日期序列化

自定义每个属性的的日期格式

你可以通过指定转化声明中的日期格式来自定义单个 Eloquent 日期属性的序列化格式:

protected $casts = [
    'birthday' => 'date:Y-m-d',
    'joined_at' => 'datetime:Y-m-d H:00',
];

通过 Carbon 全局自定义

Laravel 扩展了 Carbon 日期库以便自定义 Carbon 的 JSON 序列化格式,要自定义所有 Carbon 日期在整个应用中如何被序列化,可以使用 Carbon::serializeUsing 方法。 serializeUsing 方法接收一个闭包,该闭包返回字符串形式的日期用于 JSON 序列化:

<?php

namespace App\Providers;

use Illuminate\Support\Carbon;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        Carbon::serializeUsing(function ($carbon) {
            return $carbon->format('U');
        });
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Computer Age Statistical Inference

Computer Age Statistical Inference

Bradley Efron、Trevor Hastie / Cambridge University Press / 2016-7-21 / USD 74.99

The twenty-first century has seen a breathtaking expansion of statistical methodology, both in scope and in influence. 'Big data', 'data science', and 'machine learning' have become familiar terms in ......一起来看看 《Computer Age Statistical Inference》 这本书的介绍吧!

html转js在线工具
html转js在线工具

html转js在线工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具