W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎勵
有時(shí),需要在數(shù)組或 JSON 中添加一些數(shù)據(jù)庫中不存在字段的對應(yīng)屬性。要實(shí)現(xiàn)這個(gè)功能,首先要定義一個(gè) 修改器。
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the administrator flag for the user.
*
* @return bool
*/
public function getIsAdminAttribute()
{
return $this->attributes['admin'] === 'yes';
}
}
然后,在模型屬性 appends
中添加該屬性名。注意,盡管訪問器使用「駝峰命名法」方式定義,但是屬性名通常以「蛇形命名法」的方式來引用:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = ['is_admin'];
}
使用 append
方法追加屬性后,它將包含在模型的數(shù)組和 JSON 中。appends
數(shù)組中的屬性也將遵循模型上配置的 visible
和 hidden
設(shè)置。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: