海南旅游SAAS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.1 KiB

4 years ago
  1. <?php
  2. namespace App\Models;
  3. use App\Common\ProductStatus;
  4. use Illuminate\Database\Eloquent\Factories\HasFactory;
  5. use Illuminate\Database\Eloquent\SoftDeletes;
  6. class AgentProduct extends BaseModel
  7. {
  8. use HasFactory, SoftDeletes;
  9. protected $guarded = ['id'];
  10. public function product()
  11. {
  12. return $this->belongsTo(Product::class);
  13. }
  14. public function coupon()
  15. {
  16. return $this->hasMany(Coupon::class);
  17. }
  18. public function fav()
  19. {
  20. return $this->hasOne(UserFav::class);
  21. }
  22. public function agent()
  23. {
  24. return $this->belongsTo(Agent::class);
  25. }
  26. public function category()
  27. {
  28. return $this->belongsTo(Category::class);
  29. }
  30. public function user()
  31. {
  32. return $this->hasOne(User::class, 'id', 'verifier');
  33. }
  34. public function guide()
  35. {
  36. return $this->belongsTo(Guide::class);
  37. }
  38. public function item()
  39. {
  40. return $this->hasMany(AgentProductItem::class);
  41. }
  42. public function setChannelIdAttribute($value)
  43. {
  44. if (is_array($value)) {
  45. $this->attributes['channel_id'] = join(',', array_filter($value));
  46. }
  47. }
  48. public function setPicturesAttribute($value)
  49. {
  50. if (is_array($value)) {
  51. $this->attributes['pictures'] = json_encode(array_filter($value));
  52. }
  53. }
  54. public function setProductIdsAttribute($value)
  55. {
  56. if (is_array($value)) {
  57. $this->attributes['product_ids'] = join(',', array_filter($value));
  58. }
  59. }
  60. // 获取所有产品图片
  61. public function getPicturesAttribute($value): array
  62. {
  63. if (is_string($value)) {
  64. $value = $value ? json_decode($value, true) : [];
  65. }
  66. $this->append('picture');
  67. return $value ?? [];
  68. }
  69. // 获取第一张产品图片
  70. public function getPictureAttribute($value): string
  71. {
  72. return $this->pictures[0] ?? '';
  73. }
  74. //列表查询统一查询条件
  75. public function scopeList($query, $agent_id)
  76. {
  77. return $query->whereHas('product', function ($query) {
  78. return $query->where('status', ProductStatus::ON_SALE)->where('stock', '>', 0);
  79. })
  80. ->where(['agent_id' => $agent_id, 'status' => ProductStatus::ON_SALE])->where('stock', '>', 0)
  81. ->select('id', 'sale', 'product_id', 'price', 'original_price', 'title', 'pictures');
  82. }
  83. }