33 lines
1.0 KiB
PHP
33 lines
1.0 KiB
PHP
<?php
|
|
|
|
namespace Modules\Sites\Concerns;
|
|
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Relations\MorphToMany;
|
|
use Modules\Sites\Models\Site;
|
|
use Modules\Sites\Services\SiteManager;
|
|
|
|
trait BelongsToSites
|
|
{
|
|
public function sites(): MorphToMany
|
|
{
|
|
return $this->morphToMany(Site::class, 'content', 'site_content', 'content_id', 'site_id')->withPivot('is_primary')->withTimestamps();
|
|
}
|
|
|
|
public function scopeForCurrentSite(Builder $query): Builder
|
|
{
|
|
$site = app(SiteManager::class)->current();
|
|
|
|
return $site ? $query->whereHas('sites', fn (Builder $sites) => $sites->whereKey($site->id)) : $query;
|
|
}
|
|
|
|
public function assignToSite(Site|int $site, bool $primary = false): void
|
|
{
|
|
$id = $site instanceof Site ? $site->getKey() : $site;
|
|
if ($primary) {
|
|
$this->sites()->updateExistingPivot($this->sites()->pluck('sites.id'), ['is_primary' => false]);
|
|
}
|
|
$this->sites()->syncWithoutDetaching([$id => ['is_primary' => $primary]]);
|
|
}
|
|
}
|