DistProduct.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. // 静态方法用于查询多个产品
  30. public static function getProducts($categoryId = null, $limit = null)
  31. {
  32. $query = self::query();
  33. $query->where('enabled', 1);
  34. $query->where('dist_id', getDistId());
  35. // 如果提供了分类 ID,添加过滤条件
  36. if ($categoryId) {
  37. $query->where('category_id', $categoryId);
  38. }
  39. // 包括关联数据(图片和分类)
  40. $query->with(['images', 'distProductCategory']);
  41. // 添加排序逻辑:按 is_pinned 降序,再按 order 降序,再按 id 降序
  42. $query->orderBy('order', 'desc')
  43. ->orderBy('id', 'desc');
  44. // 如果提供了限制数量,限制查询结果
  45. if ($limit) {
  46. return $query->limit($limit)->get();
  47. }
  48. // 默认返回所有结果
  49. return $query->get();
  50. }
  51. }