源码:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; /** * 商品分类 */ class GoodsCategory extends Model { protected $fillable = ['name', 'category_image']; 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 getLevelAttribute($value) { // $data = [ // '0' => '根目录', // '1' => '二级', // '2' => '三级', // ]; // return (is_null($value)) ? $data : $data[$value]; // } /** * 测试方法 * @return [type] [description] */ public function test() { $category = GoodsCategory::where('id', 10)->first(); $data = $category->ancestors->toArray(); return $data; } }
源码:
<?php use App\Models\GoodsCategory; use Illuminate\Database\Seeder; class GoodsCategoryTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $categories = [ [ 'name' => '手机配件', 'sort' => '0', 'children' => [ [ 'name' => '手机壳', 'sort' => '0', 'children' => [ [ 'name' => '华为V10手机', 'sort' => '0', ], [ 'name' => '小米', 'sort' => '1', ], ], ], [ 'name' => '数据线', 'sort' => '4', 'children' => [ [ 'name' => '苹果数据线', 'sort' => '0', ], [ 'name' => '安卓数据线', 'sort' => '1', ], ], ], [ 'name' => '耳机', 'sort' => '0', 'children' => [ [ 'name' => '有线耳机', 'sort' => '1', ], [ 'name' => '蓝牙耳机', 'sort' => '0', ], ], ], ], ], [ 'name' => '六星果园', 'sort' => '0', 'children' => [ [ 'name' => '国产水果', 'sort' => '0', 'children' => [ [ 'name' => '苹果', 'sort' => '0', ], [ 'name' => '梨', 'sort' => '1', ], ], ], ] ] ]; foreach ($categories as $data) { $this->createCategory($data); } } public function createCategory($data, $parent = null) { // 创建一个分类 $category = new GoodsCategory([ 'name' => $data['name'], 'sort' => $data['sort'], ]); // 如果有父级参数,代表有父类目 if (!is_null($parent)) { // 将模型实例与给定的父实例关联。 $category->parent()->associate($parent); } // 保存到数据库 $category->save(); // 如果有children字段并且 children字段是一个数组 if (isset($data['children']) && is_array($data['children'])) { foreach ($data['children'] as $child) { $this->createCategory($child, $category); } } } }