'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(); } }