本文介紹了Laravel Eloquent Serialization:如何重命名屬性?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
例如,我有擴(kuò)展 Eloquent 的用戶模型.在數(shù)據(jù)庫表中,列名是user_id
.
For example, I have User model extending Eloquent. In the database table, the column name is user_id
.
閱讀后如何將結(jié)果輸出為'userId'?
How do I output the result as 'userId' after reading?
推薦答案
使用屬性訪問器添加單個別名"
您可以使用屬性訪問器來創(chuàng)建新屬性":
public function getUserIdAttribute(){
return $this->attributes['user_id'];
}
這允許您以這種方式訪問??值:$user->userId
This allows you to access the value this way: $user->userId
現(xiàn)在讓我們將值添加到數(shù)組/JSON 轉(zhuǎn)換中:
Now let's add the value to array / JSON conversion:
protected $appends = array('userId');
最后隱藏丑陋的user_id
:
protected $hidden = array('user_id');
在將模型轉(zhuǎn)換為數(shù)組或 JSON 字符串時,您還可以使用 toArray()
更改所有屬性名稱.
You can also use toArray()
to change the all attribute names when converting the model into an array or JSON string.
public function toArray(){
$array = parent::toArray();
$camelArray = array();
foreach($array as $name => $value){
$camelArray[camel_case($name)] = $value;
}
return $camelArray;
}
這篇關(guān)于Laravel Eloquent Serialization:如何重命名屬性?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!