国产chinesehdxxxx野外,国产av无码专区亚洲av琪琪,播放男人添女人下边视频,成人国产精品一区二区免费看,chinese丰满人妻videos

Eloquent ORM ―― 序列化

2018-02-24 15:38 更新

Eloquent ORM —— 序列化

1、簡介

當(dāng)構(gòu)建JSON中。

2、基本使用

2.1 轉(zhuǎn)化模型為數(shù)組

要轉(zhuǎn)化模型及其加載的關(guān)聯(lián)關(guān)系為數(shù)組,可以使用toArray方法。這個方法是遞歸的,所以所有屬性及其關(guān)聯(lián)對象屬性(包括關(guān)聯(lián)的關(guān)聯(lián))都會被轉(zhuǎn)化為數(shù)組:

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

還可以轉(zhuǎn)化集合為數(shù)組:

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

2.2 轉(zhuǎn)化模型為JSON

要轉(zhuǎn)化模型為JSON,可以使用toJson方法,和toArray一樣,toJson方法也是遞歸的,所有屬性及其關(guān)聯(lián)屬性都會被轉(zhuǎn)化為JSON:

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

你還可以轉(zhuǎn)化模型或集合為字符串,這將會自動調(diào)用toJson方法:

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

由于模型和集合在轉(zhuǎn)化為字符串的時候會被轉(zhuǎn)化為JSON,你可以從應(yīng)用的路由或控制器中直接返回Eloquent對象:

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

3、在JSON中隱藏屬性顯示

有時候你希望在模型數(shù)組或JSON顯示中限制某些屬性,比如密碼,要實現(xiàn)這個,在定義模型的時候添加一個$hidden屬性:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model{
    /**
     * 在數(shù)組中隱藏的屬性
     *
     * @var array
     */
    protected $hidden = ['password'];
}

注意:如果要隱藏關(guān)聯(lián)關(guān)系,使用關(guān)聯(lián)關(guān)系的方法名,而不是動態(tài)屬性名。

此外,可以使用visible屬性定義屬性顯示的白名單:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model{
    /**
     * 在數(shù)組中顯示的屬性
     *
     * @var array
     */
    protected $visible = ['first_name', 'last_name'];
}

4、追加值到JSON

有時候,需要添加數(shù)據(jù)庫中沒有相應(yīng)的字段到數(shù)組中,要實現(xiàn)這個,首先要定義一個訪問器

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model{
    /**
     * 為用戶獲取管理員標(biāo)識
     *
     * @return bool
     */
    public function getIsAdminAttribute()
    {
        return $this->attributes['admin'] == 'yes';
    }
}

定義好訪問器后,添加字段名到模型的appends屬性:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model{
    /**
     * 追加到模型數(shù)組表單的訪問器
     *
     * @var array
     */
    protected $appends = ['is_admin'];
}

字段被添加到appends列表之后,將會被包含到模型數(shù)組和JSON表單中,appends數(shù)組中的字段還會遵循模型中的visiblehidden設(shè)置配置。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號