84 lines
2.2 KiB
PHP
84 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Database\Factories\ConversationFactory;
|
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
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\Database\Eloquent\Relations\HasOne;
|
|
|
|
#[Fillable(['created_by_id', 'type', 'name', 'description'])]
|
|
class Conversation extends Model
|
|
{
|
|
/** @use HasFactory<ConversationFactory> */
|
|
use HasFactory;
|
|
|
|
public const string TypeDirect = 'direct';
|
|
|
|
public const string TypeGroup = 'group';
|
|
|
|
/**
|
|
* @return BelongsTo<User, $this>
|
|
*/
|
|
public function creator(): BelongsTo
|
|
{
|
|
return $this->belongsTo(User::class, 'created_by_id');
|
|
}
|
|
|
|
/**
|
|
* @return HasMany<ConversationParticipant, $this>
|
|
*/
|
|
public function participants(): HasMany
|
|
{
|
|
return $this->hasMany(ConversationParticipant::class);
|
|
}
|
|
|
|
/**
|
|
* @return BelongsToMany<User, $this>
|
|
*/
|
|
public function users(): BelongsToMany
|
|
{
|
|
return $this->belongsToMany(User::class, 'conversation_participants')
|
|
->withPivot(['role', 'joined_at', 'last_read_at', 'muted_until', 'pinned_at'])
|
|
->withTimestamps();
|
|
}
|
|
|
|
/**
|
|
* @return HasMany<Message, $this>
|
|
*/
|
|
public function messages(): HasMany
|
|
{
|
|
return $this->hasMany(Message::class);
|
|
}
|
|
|
|
/**
|
|
* @return HasOne<Message, $this>
|
|
*/
|
|
public function latestMessage(): HasOne
|
|
{
|
|
return $this->hasOne(Message::class)->latestOfMany();
|
|
}
|
|
|
|
/**
|
|
* @param Builder<Conversation> $query
|
|
* @return Builder<Conversation>
|
|
*/
|
|
public function scopeForUser(Builder $query, User|int $user): Builder
|
|
{
|
|
$userId = $user instanceof User ? $user->id : $user;
|
|
|
|
return $query->whereHas('participants', fn (Builder $participants) => $participants
|
|
->where('user_id', $userId));
|
|
}
|
|
|
|
public function isGroup(): bool
|
|
{
|
|
return $this->type === self::TypeGroup;
|
|
}
|
|
}
|