From b14d75105d14bf5a89f3384daf4ef3c05e29428a Mon Sep 17 00:00:00 2001 From: amirghasempoor Date: Wed, 25 Dec 2024 14:17:27 +0330 Subject: [PATCH] create many to many polymorphic relation --- app/Models/RoadItemsProject.php | 10 ++++--- ..._12_25_133822_create_machinables_table.php | 29 +++++++++++++++++++ ..._12_25_141411_create_rahdarables_table.php | 29 +++++++++++++++++++ 3 files changed, 64 insertions(+), 4 deletions(-) create mode 100644 database/migrations/2024_12_25_133822_create_machinables_table.php create mode 100644 database/migrations/2024_12_25_141411_create_rahdarables_table.php diff --git a/app/Models/RoadItemsProject.php b/app/Models/RoadItemsProject.php index d0a041d5..06c9dc48 100644 --- a/app/Models/RoadItemsProject.php +++ b/app/Models/RoadItemsProject.php @@ -4,6 +4,7 @@ namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\HasOne; +use Illuminate\Database\Eloquent\Relations\MorphToMany; use Illuminate\Http\UploadedFile; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; @@ -167,17 +168,18 @@ class RoadItemsProject extends Model } } - public function cmmsMachines(): BelongsToMany + public function cmmsMachines(): MorphToMany { - return $this->belongsToMany(CMMSMachine::class, + return $this->morphToMany(CMMSMachine::class, + 'machinable', 'cmms_machine_road_items_project', 'road_items_project_id', 'machine_id' ); } - public function rahdaran(): BelongsToMany + public function rahdaran(): MorphToMany { - return $this->belongsToMany(Rahdaran::class,'rahdaran_road_items_project'); + return $this->morphToMany(Rahdaran::class, 'rahdarable', 'rahdaran_road_items_project'); } } diff --git a/database/migrations/2024_12_25_133822_create_machinables_table.php b/database/migrations/2024_12_25_133822_create_machinables_table.php new file mode 100644 index 00000000..4e81635b --- /dev/null +++ b/database/migrations/2024_12_25_133822_create_machinables_table.php @@ -0,0 +1,29 @@ +id(); + $table->foreignId('machine_id')->constrained('cmms_machines')->noActionOnDelete(); + $table->morphs('machinable'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('machinable'); + } +}; diff --git a/database/migrations/2024_12_25_141411_create_rahdarables_table.php b/database/migrations/2024_12_25_141411_create_rahdarables_table.php new file mode 100644 index 00000000..bdc37b30 --- /dev/null +++ b/database/migrations/2024_12_25_141411_create_rahdarables_table.php @@ -0,0 +1,29 @@ +id(); + $table->foreignId('rahdar_id')->constrained('rahdaran')->noActionOnDelete(); + $table->morphs('rahdarable'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('rahdarables'); + } +};