Files
zh-chat-server/app/Models/Dynamic.php
2022-11-01 16:39:45 +08:00

125 lines
3.0 KiB
PHP

<?php
namespace App\Models;
use App\Models\Traits\BelongsToUser;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class Dynamic extends Model
{
use SoftDeletes;
use BelongsToUser;
protected $casts = [
'pictures' => 'json',
];
public function getPicturesUrlAttribute(): array
{
$pictures = $this->getAttribute('pictures');
if (empty($pictures)) {
return [];
}
return collect($pictures)->map(function ($picture) {
return $this->parseImageUrl($picture);
})->toArray();
}
/**
* Notes : 解析图片文件的实际展示地址
*
* @Date : 2021/3/16 4:53 下午
* @Author : < Jason.C >
* @param string|null $image
* @return string
*/
protected function parseImageUrl(?string $image): string
{
if (empty($image)) {
return '';
} elseif (Str::startsWith($image, 'http')) {
return $image;
} else {
return Storage::url($image);
}
}
public function isLikedBy(User $user): bool
{
if ($this->relationLoaded('likers')) {
return $this->likers->contains($user);
}
$likes = $this->likers()->where('user_id', $user->getKey())->first();
return (bool) $likes;
}
/**
* Notes : 点赞用户
*
* @Date : 2021/4/23 4:12 下午
* @Author : < Jason.C >
* @return BelongsToMany
*/
public function likers(): BelongsToMany
{
return $this->belongsToMany(
User::class,
'likes',
'likeable_id',
'user_id'
)->where('likeable_type', $this->getMorphClass());
}
/**
* Notes : 是否被某人评论过了
*
* @Date : 2021/4/16 3:44 下午
* @Author : < Jason.C >
* @param Model $user
* @return bool
*/
public function isCommentedBy(Model $user): bool
{
if ($this->relationLoaded('commenters')) {
return $this->commenters->contains($user);
}
return $this->comments()->where('user_id', $user->getKey())->exists();
}
/**
* Notes : 评论记录
*
* @Date : 2021/4/16 3:44 下午
* @Author : < Jason.C >
* @return MorphMany
*/
public function comments(): MorphMany
{
return $this->morphMany(Comment::class, 'commentable');
}
/**
* Notes : 评论用户
*
* @Date : 2021/4/23 4:12 下午
* @Author : < Jason.C >
* @return BelongsToMany
*/
public function commenters(): BelongsToMany
{
return $this->belongsToMany(
User::class,
'comments',
'commentable_id',
'user_id'
)->where('commentable_type', $this->getMorphClass());
}
}