75 lines
1.7 KiB
PHP
75 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Models\Traits\HasOneCover;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
use Dcat\Admin\Traits\ModelTree;
|
|
|
|
class Category extends Model
|
|
{
|
|
|
|
use HasOneCover, ModelTree;
|
|
|
|
public const TYPE_SHOW = 'show';
|
|
public const TYPE_ARTICLE = 'article';
|
|
public const TYPE_ADVERT = 'advert';
|
|
public const TYPE_WEB = 'web';
|
|
public const TYPES = [
|
|
self::TYPE_ARTICLE => '文章列表',
|
|
self::TYPE_SHOW => '文章详情',
|
|
self::TYPE_ADVERT => '图片',
|
|
self::TYPE_WEB => '跳转链接',
|
|
];
|
|
|
|
public function getLinkAttribute()
|
|
{
|
|
return route('category.show', $this);
|
|
}
|
|
|
|
/**
|
|
* 关联的数据
|
|
* @return [type] [description]
|
|
*/
|
|
public function relations()
|
|
{
|
|
switch ($this->type) {
|
|
case self::TYPE_SHOW:
|
|
return $this->hasOne(Article::class, 'id', 'article_id');
|
|
break;
|
|
case self::TYPE_ARTICLE:
|
|
return $this->hasMany(Article::class);
|
|
break;
|
|
case self::TYPE_ADVERT:
|
|
return $this->hasMany(Advert::class);
|
|
break;
|
|
default:
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public function parent(): BelongsTo
|
|
{
|
|
return $this->belongsTo(__CLASS__)->withDefault(['name' => '顶级分类']);
|
|
}
|
|
|
|
public function children(): HasMany
|
|
{
|
|
return $this->hasMany(__CLASS__, 'parent_id');
|
|
}
|
|
|
|
//查找顶级分类
|
|
public function getTop()
|
|
{
|
|
$parent = $this;
|
|
|
|
while ($parent->parent_id != 0) {
|
|
$parent = $parent->parent;
|
|
}
|
|
|
|
return $parent;
|
|
}
|
|
|
|
}
|