| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- <?php
- namespace App\Models;
- use Illuminate\Database\Eloquent\Factories\HasFactory;
- use Illuminate\Database\Eloquent\Model;
- class Category extends Model
- {
- use HasFactory;
- protected $fillable = [
- 'parent_id',
- 'name',
- 'enabled'
- ];
- public function parent()
- {
- return $this->belongsTo(Category::class);
- }
- public function childs() {
- return $this->hasMany(\App\Models\Category::class,'parent_id','id') ;
- }
- public function getTree()
- {
- $str = '';
- if ($this->parent_id != null)
- {
- $a = $this->recursiveName($this->parent_id, array($this->name));
- $a = array_reverse($a);
- $str = implode(" - ", $a);
- }
- else
- {
- $str = $this->name;
- }
- return $str;
- }
- public function recursiveName($parent_id, $array)
- {
- $x = \App\Models\Category::findOrFail($parent_id);
- $array[] = $x->name;
- if ($x->parent_id != null)
- {
- return $this->recursiveName($x->parent_id, $array);
- }
- else
- {
- return $array;
- }
- }
- }
|