69 lines
1.8 KiB
PHP
69 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Enums\InteractionType;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
use Illuminate\Support\Facades\Auth;
|
|
|
|
class Deal extends Model
|
|
{
|
|
public function broker(): BelongsTo
|
|
{
|
|
return $this->belongsTo(User::class, 'user_id');
|
|
}
|
|
|
|
public function category(): BelongsTo
|
|
{
|
|
return $this->belongsTo(DealCategory::class, 'deal_category_id');
|
|
}
|
|
|
|
public function interactions(): HasMany
|
|
{
|
|
return $this->hasMany(Interaction::class);
|
|
}
|
|
|
|
/**
|
|
* Get deals that are active
|
|
*/
|
|
public function scopeWithActiveDeals(Builder $query): Builder
|
|
{
|
|
return $query->where('active', true);
|
|
}
|
|
|
|
/**
|
|
* Get if the current user has liked or favorite the deal
|
|
*/
|
|
public function scopeWithCurrentUserInteractions(Builder $query): Builder
|
|
{
|
|
return $query->withExists([
|
|
'interactions as is_liked' => function ($query) {
|
|
$query->where('user_id', Auth::id())
|
|
->where('type', InteractionType::Like);
|
|
},
|
|
'interactions as is_favorite' => function ($query) {
|
|
$query->where('user_id', Auth::id())
|
|
->where('type', InteractionType::Favorite);
|
|
},
|
|
]);
|
|
}
|
|
|
|
public function scopeWithLikes(Builder $query): Builder
|
|
{
|
|
return $query->withCount([
|
|
'interactions as total_likes' => function ($query) {
|
|
$query->where('type', InteractionType::Like);
|
|
},
|
|
]);
|
|
}
|
|
|
|
public function reports(): BelongsToMany
|
|
{
|
|
return $this->belongsToMany(Report::class);
|
|
}
|
|
}
|