'order', 'sort_when_creating' => true, ]; function __construct(array $attributes = []) { parent::__construct($attributes); $this->modelType = "TAG"; } public function tags() { return $this->belongsToMany('App\Models\Tag', 'tag_tag', 'parent_id', 'tag_id'); } public function tags2() { return $this->belongsToMany('App\Models\Tag', 'tag_tag', 'tag_id', 'parent_id'); } public function children() { return $this->belongsToMany('App\Models\Tag', 'tag_tag', 'tag_id', 'parent_id') ->where('tag_tag.parent_id', '!=', DB::raw('`tag_tag`.`tag_id`')); } public function scopeIsRootElement($query) { return $query->doesnthave('tags'); // ->doesnthave('tags2'); return $query->join('tag_tag as tag_tag', function($join){ $join->on('tag_tag.parent_id', 'tags.id') ->where('tag_tag.parent_id', DB::raw('`tag_tag`.`tag_id`')); }) ->addSelect('tag_tag.parent_id'); } /**********/ /* Scopes */ /**********/ public function scopeIsType($query, $type) { return $query->where('type', $type); } }