<?php
declare (strict_types = 1);

namespace app\openapi\model;

use app\common\model\ArticleBaseModel;
use think\facade\Db;

/**
 * 文章模型
 * @mixin \think\Model
 */
class ArticleModel extends ArticleBaseModel
{
    // 关联分类
    public function category()
    {
        return $this->belongsTo(ArticleCategoryModel::class, 'category_id', 'id');
    }

    // 所属语言范围查询
    public function scopeLanguage($query, $language = 'zh-cn')
    {
        $query->whereExists(function($subquery) use($language) {
            $lang_model = new LanguageModel;
            $subquery->model($lang_model)
                ->name($lang_model->getName())
                ->field(['id'])
                ->where('id', '=', Db::raw($this->getTable() . '.language_id'))
                ->where('code', '=', $language);
        });
    }

    // 所属分类范围查询
    public function scopeCategoryId($query, $category_id)
    {
        if (is_null($category_id)) return;
        $query->where('category_id', '=', $category_id);
    }
}
