feat(attachments): add HasAttachments trait to manage attachment relationships
This commit is contained in:
18
app/Domains/Attachable/Models/Concerns/HasAttachments.php
Normal file
18
app/Domains/Attachable/Models/Concerns/HasAttachments.php
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Attachable\Models\Concerns;
|
||||||
|
|
||||||
|
use App\Domains\Attachable\Models\Attachment;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
||||||
|
|
||||||
|
trait HasAttachments
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return MorphMany<Attachment, Model>
|
||||||
|
*/
|
||||||
|
public function attachments(): MorphMany
|
||||||
|
{
|
||||||
|
return $this->morphMany(Attachment::class, 'attachable');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,9 +20,7 @@ class AttachmentTest extends TestCase
|
|||||||
'dominio' => 'acme.com',
|
'dominio' => 'acme.com',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$attachment = Attachment::query()->create([
|
$attachment = $tenant->attachments()->create([
|
||||||
'attachable_type' => $tenant->getMorphClass(),
|
|
||||||
'attachable_id' => $tenant->getKey(),
|
|
||||||
'path' => 'attachments/acme/logo.png',
|
'path' => 'attachments/acme/logo.png',
|
||||||
'filename' => 'logo.png',
|
'filename' => 'logo.png',
|
||||||
'type' => AttachmentType::Image,
|
'type' => AttachmentType::Image,
|
||||||
@@ -32,14 +30,18 @@ class AttachmentTest extends TestCase
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
$this->assertSame(AttachmentType::Image, $attachment->type);
|
$this->assertSame(AttachmentType::Image, $attachment->type);
|
||||||
|
$this->assertTrue($tenant->attachments->contains($attachment));
|
||||||
$this->assertDatabaseHas('attachments', [
|
$this->assertDatabaseHas('attachments', [
|
||||||
'id' => $attachment->id,
|
'id' => $attachment->id,
|
||||||
|
'attachable_type' => $tenant->getMorphClass(),
|
||||||
|
'attachable_id' => $tenant->getKey(),
|
||||||
'type' => AttachmentType::Image->value,
|
'type' => AttachmentType::Image->value,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$freshAttachment = Attachment::query()->findOrFail($attachment->id);
|
$freshAttachment = Attachment::query()->findOrFail($attachment->id);
|
||||||
|
|
||||||
$this->assertSame(AttachmentType::Image, $freshAttachment->type);
|
$this->assertSame(AttachmentType::Image, $freshAttachment->type);
|
||||||
|
$this->assertTrue($freshAttachment->attachable->is($tenant));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_it_requires_attachment_type(): void
|
public function test_it_requires_attachment_type(): void
|
||||||
|
|||||||
Reference in New Issue
Block a user