urlsnail/app/Models/Bookmark.php

42 lines
972 B
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Bookmark extends Model
{
use HasFactory;
protected $table = 'bookmarks';
protected $with = ['tags'];
public function syncTagsFromString(string $tags_string): array
{
$tags_input = trim($tags_string);
$tags_input = preg_split('/\s+/', $tags_input);
$tags = [];
foreach ($tags_input as $tag_input) {
$tag = Tag::firstOrCreate(['name' => $tag_input]);
$tags[$tag->id] = true;
}
return $this->tags()->sync(array_keys($tags));
}
public function tags(): BelongsToMany
{
return $this->belongsToMany(Tag::class);
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}