完善功能
This commit is contained in:
67
web10/app/Models/AdSlot.php
Normal file
67
web10/app/Models/AdSlot.php
Normal file
@@ -0,0 +1,67 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user