feat(01-01): add Member notes relationship, morph map, and NoteFactory
- Add notes() morphMany relationship to Member model (ordered by created_at desc)
- Register morph map in AppServiceProvider ('member' => Member::class)
- Create NoteFactory with forMember() and byAuthor() state methods
This commit is contained in:
@@ -4,6 +4,7 @@ namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
|
||||
class Member extends Model
|
||||
@@ -110,6 +111,14 @@ class Member extends Model
|
||||
return $this->hasMany(Member::class, 'guardian_member_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* 會員備註(管理員可對任一會員新增備註)
|
||||
*/
|
||||
public function notes(): MorphMany
|
||||
{
|
||||
return $this->morphMany(Note::class, 'notable')->orderBy('created_at', 'desc');
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否為病友
|
||||
*/
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Models\Document;
|
||||
use App\Models\Member;
|
||||
use App\Observers\DocumentObserver;
|
||||
use Illuminate\Database\Eloquent\Relations\Relation;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
@@ -21,6 +23,11 @@ class AppServiceProvider extends ServiceProvider
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
// Register morph map to protect against namespace refactoring
|
||||
Relation::enforceMorphMap([
|
||||
'member' => Member::class,
|
||||
]);
|
||||
|
||||
Document::observe(DocumentObserver::class);
|
||||
}
|
||||
}
|
||||
|
||||
44
database/factories/NoteFactory.php
Normal file
44
database/factories/NoteFactory.php
Normal file
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Factories;
|
||||
|
||||
use App\Models\Member;
|
||||
use App\Models\Note;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
|
||||
class NoteFactory extends Factory
|
||||
{
|
||||
protected $model = Note::class;
|
||||
|
||||
public function definition(): array
|
||||
{
|
||||
return [
|
||||
'notable_type' => 'member', // Uses morph map alias
|
||||
'notable_id' => Member::factory(),
|
||||
'content' => $this->faker->paragraph(),
|
||||
'author_user_id' => User::factory(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the note to belong to a specific member
|
||||
*/
|
||||
public function forMember(Member $member): static
|
||||
{
|
||||
return $this->state(fn () => [
|
||||
'notable_type' => 'member',
|
||||
'notable_id' => $member->id,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the note to be authored by a specific user
|
||||
*/
|
||||
public function byAuthor(User $user): static
|
||||
{
|
||||
return $this->state(fn () => [
|
||||
'author_user_id' => $user->id,
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user