123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- <?php
- namespace App\Models;
- use Illuminate\Database\Eloquent\Factories\HasFactory;
- use Illuminate\Database\Eloquent\Model;
- class DistProduct extends Model
- {
- use HasFactory;
- protected $table = 'dist_product';
- protected $casts = [
- 'created_at' => 'datetime:Y-m-d H:i:s',
- 'updated_at' => 'datetime:Y-m-d H:i:s',
- 'parameters' => 'json', // 将 attributes 字段转换为数组
- ];
- // 定义与分类的一对一关系
- public function distProductCategory()
- {
- return $this->hasOne(DistProductCategory::class, 'id', 'category_id');
- }
- // 定义与图片的一对多关系
- public function images()
- {
- return $this->hasMany(DistProductImage::class, 'product_id')->orderBy('order', 'asc')->orderBy('id', 'asc');;
- }
- // 静态方法用于查询单个产品
- public static function getProduct($productId)
- {
- return self::where('enabled', 1)->where('dist_id', getDistId())->with('images')->find($productId);
- }
- public static function getProductSlug($slug)
- {
- return self::where('enabled', 1)->where('dist_id', getDistId())->where('slug', $slug)->with('images')->first();
- }
- // 静态方法用于查询多个产品
- public static function getProducts($categoryId = null, $limit = null)
- {
- $query = self::query();
- $query->where('enabled', 1);
- $query->where('dist_id', getDistId());
- // 如果提供了分类 ID,添加过滤条件
- if ($categoryId) {
- $query->where('category_id', $categoryId);
- }
- // 包括关联数据(图片和分类)
- $query->with(['images', 'distProductCategory']);
- // 添加排序逻辑:按 is_pinned 降序,再按 order 降序,再按 id 降序
- $query->orderBy('order', 'desc')
- ->orderBy('id', 'desc');
- // 如果提供了限制数量,限制查询结果
- if ($limit) {
- return $query->limit($limit)->get();
- }
- // 默认返回所有结果
- return $query->get();
- }
- }
|