Files
ai-nav/web10/app/Models/AdSlot.php

68 lines
1.5 KiB
PHP
Raw Normal View History

2026-02-07 22:55:07 +08:00
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
class AdSlot extends Model
{
use HasFactory;
protected $fillable = [
'key',
'name',
'description',
'is_active',
'max_items',
'sort',
];
protected $casts = [
'is_active' => 'boolean',
];
public function ads()
{
return $this->hasMany(Ad::class);
}
public static function getActiveAds(string $key): Collection
{
$slot = static::query()
->where('key', $key)
->where('is_active', true)
->first();
if (!$slot) {
return collect();
}
$now = now();
$query = $slot->ads()
->where('is_active', true)
->where(function ($inner) use ($now) {
$inner->whereNull('starts_at')
->orWhere('starts_at', '<=', $now);
})
->where(function ($inner) use ($now) {
$inner->whereNull('ends_at')
->orWhere('ends_at', '>=', $now);
})
->orderBy('sort');
if ($slot->max_items) {
$query->limit($slot->max_items);
}
$ads = $query->with('product')->get();
if ($ads->isNotEmpty()) {
Ad::query()->whereIn('id', $ads->pluck('id'))->increment('view_count');
}
return $ads;
}
}