数据库:模型序列化

Introduction

在构建 JSON API 时,您通常需要将模型和关系转换为数组或 JSON。模型包括进行这些转换以及控制序列化中包含哪些属性的便捷方法。

基本用法

将模型转换为数组

转换模型及其加载relationships 到一个数组,你可以使用toArray 方法。这个方法是递归的,所以所有的属性和所有的关系(包括关系的关系)都会被转换为数组:

$user = User::with('roles')->first();

return $user->toArray();

您也可以转换collections 到数组:

$users = User::all();

return $users->toArray();

将模型转换为 JSON

要将模型转换为 JSON,您可以使用toJson 方法。喜欢toArray, 这toJson 方法是递归的,因此所有属性和关系都将转换为 JSON:

$user = User::find(1);

return $user->toJson();

或者,您可以将模型或集合转换为字符串,这将自动调用toJson 方法:

$user = User::find(1);

return (string) $user;

由于模型和集合在转换为字符串时会转换为 JSON,因此您可以直接从应用程序的路由、AJAX 处理程序或控制器返回模型对象:

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

隐藏 JSON 的属性

有时您可能希望限制模型数组或 JSON 表示中包含的属性,例如密码。为此,添加一个$hidden 模型的属性定义:

<?php namespace Acme\Blog\Models;

use Model;

class User extends Model
{
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = ['password'];
}

或者,您可以使用$visible 属性定义应包含在模型数组和 JSON 表示中的属性白名单:

class User extends Model
{
    /**
     * The attributes that should be visible in arrays.
     *
     * @var array
     */
    protected $visible = ['first_name', 'last_name'];
}

将值附加到 JSON

有时,您可能需要添加在数据库中没有对应列的数组属性。为此,首先定义一个accessor 对于价值:

class User extends Model
{
    /**
     * Get the administrator flag for the user.
     *
     * @return bool
     */
    public function getIsAdminAttribute()
    {
        return $this->attributes['admin'] == 'yes';
    }
}

创建访问器后,将属性名称添加到appends 模型属性:

class User extends Model
{
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['is_admin'];
}

一旦属性被添加到appends 列表,它将包含在模型的数组和 JSON 形式中。中的属性appends 阵列也将尊重visiblehidden 模型上配置的设置。

豫ICP备18041297号-2