<?php
declare (strict_types = 1);

namespace app\openapi\model;

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

/**
 * 产品模型
 * @mixin \think\Model
 */
class ProductModel extends ProductBaseModel
{
    // 关联分类
    public function category()
    {
        return $this->belongsTo(ProductCategoryModel::class, 'category_id', 'id');
    }

    // 关联产品参数
    public function params()
    {
        return $this->hasMany(ProductParamsModel::class, 'product_id', 'id');
    }

    // 关联sku
    public function skus()
    {
        return $this->hasMany(ProductSkuModel::class, 'product_id', 'id');
    }

    // 关联购买链接
    public function links()
    {
        return $this->hasMany(ProductPurchaseLinkModel::class, 'product_id', 'id');
    }

    // 关联相关产品
    public function related()
    {
        return $this->hasMany(ProductRelatedModel::class, 'product_id', 'id');
    }

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

    // 根据category_id范围查询
    public function scopeCategoryId($query, $category_id)
    {
        $query->where('category_id', '=', $category_id);
    }
}
