<?php
declare (strict_types = 1);

namespace app\index\model;

use app\common\model\ProductCategoryBaseModel;
use think\model\concern\SoftDelete;

/**
 * 产品分类模型
 * @mixin \think\Model
 */
class ProductCategoryModel extends ProductCategoryBaseModel
{
    // 启用软件删除
    use SoftDelete;
    // 软件删除时间字段
    protected $deleteTime = 'deleted_at';

    // 关联产品推荐
    public function recommends()
    {
        return $this->hasMany(ProductCategoryRecommendModel::class, 'category_id', 'id');
    }

    // 所属语言范围查询
    public function scopeLanguage($query, $language)
    {
        $query->where('language_id', '=', $language);
    }

    // 显示的分类范围查询
    public function scopeDisplayed($query)
    {
        $query->where('is_show', '=', 1);
    }

    // 所属所有子分类范围查询
    public function scopeChild($query, $id, $merge_self = false)
    {
        $query->where(function($q) use($id, $merge_self) {
            $q->where('pid', '=', $id);
            if ($merge_self) {
                $q->whereOr('id', '=', $id);
            }
        });
    }

    // 所属所有子孙分类范围查询
    public function scopeChildren($query, $id)
    {
        $query->whereRaw('FIND_IN_SET(:id, path)', ['id' => $id]);
    }
}
