author: Ka Ka
WeChat: fangkangfk
This is material.
Database:
Source code:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; /** * Commodity classification */ class GoodsCategory extends Model { protected $fillable = ['name', 'category_image']; protected $appends = ['levels']; public function parent() { //Backward correlation return $this->belongsTo(GoodsCategory::class); } public function children() { //One to many return $this->hasMany(GoodsCategory::class, 'parent_id'); } //Define an accessor to get the ID value of all ancestor categories public function getPossessIdsAttribute() { //Array? Filter removes null values from the array return array_filter(explode('-', trim($this->possess, '-'))); } //Define an accessor, get ancestor categories and sort them hierarchically public function getAncestorsAttribute() { return GoodsCategory::query() ->whereIn('id', $this->possess_ids) //Sort by level ->orderBy('level')->get(); } //Define an accessor to get the names of all ancestor categories separated by - and the names of the current category public function getFullNameAttribute() { return $this->ancestors //Get all ancestor classes ->pluck('name') //Get the name field of the ancestor class as an array ->push($this->name)//Get the name field of the current category and add it to the end of the array ->implode(' - '); //Use - match to form a string of array values } public function getLevelsAttribute($value) { $data = [ '0' => 'root directory', '1' => 'second level', '2' => 'Level three', ]; // return (is_null($value)) ? $data : $data[$value]; return (is_null($this->attributes['level'])) ? $data : $data[$this->attributes['level']]; } /** * test method * @return [type] [description] */ public function test() { $category = GoodsCategory::where('id', 105)->first(); $data = $category->ancestors->toArray(); return $data; } }
Let's take a look at these two methods. Test is a test method.
Visit to find out the data
You can see that the accessor set above is not available in the database field. So this is a custom catcher. Write down a detected one to test.
I wrote a kaka's catcher
Then visit
This shows that we can use a custom accessor to modify the data.