DistProduct.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. class DistProduct extends Model
  6. {
  7. use HasFactory;
  8. protected $table = 'dist_product';
  9. protected $casts = [
  10. 'created_at' => 'datetime:Y-m-d H:i:s',
  11. 'updated_at' => 'datetime:Y-m-d H:i:s',
  12. 'parameters' => 'json', // 将 attributes 字段转换为数组
  13. ];
  14. // 定义与分类的一对一关系
  15. public function distProductCategory()
  16. {
  17. return $this->hasOne(DistProductCategory::class, 'id', 'category_id');
  18. }
  19. // 定义与图片的一对多关系
  20. public function images()
  21. {
  22. return $this->hasMany(DistProductImage::class, 'product_id')->orderBy('order', 'asc')->orderBy('id', 'asc');;
  23. }
  24. // 静态方法用于查询单个产品
  25. public static function getProduct($productId)
  26. {
  27. return self::where('enabled', 1)->where('dist_id', getDistId())->with('images')->find($productId);
  28. }
  29. public static function getProductSlug($slug)
  30. {
  31. return self::where('enabled', 1)->where('dist_id', getDistId())->where('slug', $slug)->with('images')->first();
  32. }
  33. // 静态方法用于查询多个产品
  34. public static function getProducts($categoryId = null, $limit = null)
  35. {
  36. $query = self::query();
  37. $query->where('enabled', 1);
  38. $query->where('dist_id', getDistId());
  39. // 如果提供了分类 ID,添加过滤条件
  40. if ($categoryId) {
  41. $query->where('category_id', $categoryId);
  42. }
  43. // 包括关联数据(图片和分类)
  44. $query->with(['images', 'distProductCategory']);
  45. // 添加排序逻辑:按 is_pinned 降序,再按 order 降序,再按 id 降序
  46. $query->orderBy('order', 'desc')
  47. ->orderBy('id', 'desc');
  48. // 如果提供了限制数量,限制查询结果
  49. if ($limit) {
  50. return $query->limit($limit)->get();
  51. }
  52. // 默认返回所有结果
  53. return $query->get();
  54. }
  55. }