| 
						 | 
						<?php
namespace App\Models;
use App\Common\ProductStatus;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\SoftDeletes;
class AgentProduct extends BaseModel{    use HasFactory, SoftDeletes;
	protected $guarded = ['id'];
    public function product()	{		return $this->belongsTo(Product::class);	}
	public function coupon()	{		return $this->hasMany(Coupon::class);	}
	public function agent()	{		return $this->belongsTo(Agent::class)->withTrashed();	}
	public function category()	{		return $this->belongsTo(Category::class);	}
	public function user()	{		return $this->hasOne(User::class, 'id', 'verifier');	}
	public function guide()	{		return $this->belongsTo(Guide::class)->withTrashed();	}
	public function item()	{		return $this->hasMany(AgentProductItem::class);	}
	public function agentCloudProduct()	{		return $this->belongsTo(self::class, 'agent_cloud_pid', 'id');	}
	public function setChannelIdAttribute($value)	{		$this->attributes['channel_id'] = is_array($value) ? join(',', array_filter($value)) : $value;	}
	public function setPicturesAttribute($value)	{		$this->attributes['pictures'] = is_array($value) ? (json_encode(array_filter($value)) ?? '[]') : '[]';	}
	public function setProductIdsAttribute($value)	{		$this->attributes['product_ids'] = is_array($value) ? join(',', array_filter($value)) : $value;	}
	// 获取所有产品图片
	public function getPicturesAttribute($value): array	{		if (is_string($value)) {			$value = $value ? json_decode($value, true) : [];		}		$this->append('picture');		return $value ?? [];	}
	// 获取第一张产品图片
	public function getPictureAttribute($value): string	{		return $this->pictures[0] ?? '';	}
	//列表查询统一查询条件
	public static function list($agent_id)	{		return static::withoutGlobalScope('orderById')			->whereDoesntHave('agentProductItem', function ($query) {				return $query->whereHas('product', function ($query) {					return $query->where('stock', '<=', 0)->orWhere('status', '<>', ProductStatus::ON_SALE);				});			})			->where('stock', '>', 0)->where(['agent_id' => $agent_id, 'status' => ProductStatus::ON_SALE])			->select('id', 'sale', 'product_id', 'price', 'original_price', 'title', 'pictures');	}
	public function agentProductItem()	{		return $this->hasOne(AgentProductItem::class);	}}
  |