牛骨文教育服务平台(让学习变的简单)

Eloquent ORM —— 序列化

1、简介

当构建JSON中。

2、基本使用

2.1 转化模型为数组

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

$user = AppUser::with("roles")->first();
return $user->toArray();

还可以转化集合为数组:

$users = AppUser::all();
return $users->toArray();

2.2 转化模型为JSON

要转化模型为JSON,可以使用toJson方法,和toArray一样,toJson方法也是递归的,所有属性及其关联属性都会被转化为JSON:

$user = AppUser::find(1);
return $user->toJson();

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

$user = AppUser::find(1);
return (string) $user;

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

Route::get("users", function () {
    return AppUser::all();
});

3、在JSON中隐藏属性显示

有时候你希望在模型数组或JSON显示中限制某些属性,比如密码,要实现这个,在定义模型的时候添加一个$hidden属性:

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

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

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

此外,可以使用visible属性定义属性显示的白名单:

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

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

4、追加值到JSON

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

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

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

定义好访问器后,添加字段名到模型的appends属性:

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

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

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