author:咔咔php
WeChat:fangkangfk數據庫
這是素材數組
數據庫:app
源碼: 測試
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; /** * 商品分類 */ class GoodsCategory extends Model { protected $fillable = ['name', 'category_image']; protected $appends = ['levels']; public function parent() { //反向關聯 return $this->belongsTo(GoodsCategory::class); } public function children() { //一對多 return $this->hasMany(GoodsCategory::class, 'parent_id'); } //定義一個訪問器,獲取全部祖先類目的ID值 public function getPossessIdsAttribute() { //array_filter 將數組中的空值移除 return array_filter(explode('-', trim($this->possess, '-'))); } //定義一個訪問器,獲取祖先類目並按層級排序 public function getAncestorsAttribute() { return GoodsCategory::query() ->whereIn('id', $this->possess_ids) //按層級排序 ->orderBy('level')->get(); } //定義一個訪問器,獲取以 - 爲分隔的全部祖先類目的名稱以及當前類目的名稱 public function getFullNameAttribute() { return $this->ancestors //獲取全部祖先類 ->pluck('name') //獲取祖先類目的name 字段爲一個數組 ->push($this->name)//獲取當前類目的 name 字段加到數組的末尾 ->implode(' - '); //用 - 符合將數組的值組成一個字符串 } public function getLevelsAttribute($value) { $data = [ '0' => '根目錄', '1' => '二級', '2' => '三級', ]; // return (is_null($value)) ? $data : $data[$value]; return (is_null($this->attributes['level'])) ? $data : $data[$this->attributes['level']]; } /** * 測試方法 * @return [type] [description] */ public function test() { $category = GoodsCategory::where('id', 105)->first(); $data = $category->ancestors->toArray(); return $data; } }
咱們能夠看一下這倆個方法,test是一個測試方法this
訪問,能夠查出數據來spa
能夠看到上邊設置的獲取器是數據庫字段裏邊沒有的。那麼這就是一個自定義的獲取器,下來寫一個檢測的進行測試code
寫了一個kaka的獲取器排序
而後訪問ip
這就說明了,咱們可使用自定義的獲取器來修改數據