From 9b9bd4ff7b253ddf7d1a3546b344fc11cfcf4ff5 Mon Sep 17 00:00:00 2001 From: bad Date: Wed, 8 Dec 2021 21:29:28 +0100 Subject: [PATCH] Make images column polmorphic --- app/Models/Image.php | 4 +++ app/Models/Product.php | 2 +- .../2021_12_08_183713_make_images_morph.php | 35 +++++++++++++++++++ .../2021_12_08_183713_morph_images.php | 35 +++++++++++++++++++ 4 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 database/migrations/2021_12_08_183713_make_images_morph.php create mode 100644 database/migrations/2021_12_08_183713_morph_images.php diff --git a/app/Models/Image.php b/app/Models/Image.php index d03a9e6..654e501 100644 --- a/app/Models/Image.php +++ b/app/Models/Image.php @@ -18,4 +18,8 @@ class Image extends Model { return Storage::url($this->path); } + + public function imageable() { + $this->morphTo(); + } } diff --git a/app/Models/Product.php b/app/Models/Product.php index 6e4dc39..a701c61 100644 --- a/app/Models/Product.php +++ b/app/Models/Product.php @@ -13,7 +13,7 @@ class Product extends Model public function images() { - return $this->hasMany(Image::class, "product_uuid", "uuid"); + return $this->morphMany(Image::class, 'imageable'); } protected $fillable = [ diff --git a/database/migrations/2021_12_08_183713_make_images_morph.php b/database/migrations/2021_12_08_183713_make_images_morph.php new file mode 100644 index 0000000..7a3f16e --- /dev/null +++ b/database/migrations/2021_12_08_183713_make_images_morph.php @@ -0,0 +1,35 @@ +uuidMorphs("imageable"); + }); + Schema::table("images", function(Blueprint $table) { + DB::table("images")->update(['imageable_id'=>DB::raw('`product_uuid`')], ['imageable_type' => "App\Models\Product"]); + $table->dropConstrainedForeignId("product_uuid"); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // Ehh don't wanna bother + } +} diff --git a/database/migrations/2021_12_08_183713_morph_images.php b/database/migrations/2021_12_08_183713_morph_images.php new file mode 100644 index 0000000..b517403 --- /dev/null +++ b/database/migrations/2021_12_08_183713_morph_images.php @@ -0,0 +1,35 @@ +uuidMorphs("imageable"); + }); + Schema::table("images", function(Blueprint $table) { + DB::table("images")->update(['imageable_id'=>DB::raw('`product_uuid`')], ['imageable_type' => "App\Models\Product"]); + $table->dropConstrainedForeignId("product_uuid"); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + // Ehh don't wanna bother + } +}