duplicate product

This commit is contained in:
Edward Yang 2022-08-11 17:11:01 +08:00
parent 80140aa9d6
commit 4d0e0b2b86
2 changed files with 33 additions and 2 deletions

View File

@ -22,6 +22,11 @@ class Product extends Base
return $this->belongsToMany(Category::class, ProductCategory::class)->withTimestamps();
}
public function productCategories()
{
return $this->hasMany(ProductCategory::class);
}
public function description()
{
return $this->hasOne(ProductDescription::class)->where('locale', locale());
@ -42,9 +47,9 @@ class Product extends Base
return $this->hasOne(ProductSku::Class)->where('is_default', 1);
}
public function manufacturer()
public function brand()
{
return $this->hasOne(Brand::Class, 'id', 'manufacturer_id');
return $this->belongsTo(Brand::Class, 'brand_id', 'id');
}
public function getPriceFormattedAttribute(): string

View File

@ -2,6 +2,7 @@
namespace Database\Seeders;
use Beike\Models\Product;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
@ -10,9 +11,34 @@ class DatabaseSeeder extends Seeder
* Seed the application's database.
*
* @return void
* @throws \Throwable
*/
public function run()
{
// \App\Models\User::factory(10)->create();
// $this->duplicate();
}
/**
* @throws \Throwable
*/
private function duplicate(): void
{
$baseProduct = Product::with(['productCategories', 'descriptions', 'skus'])->findOrFail(2);
$newProduct = $baseProduct->replicate();
$newProduct->saveOrFail();
$newProductId = $newProduct->id;
if ($newProductId) {
$relations = $baseProduct->getRelations();
foreach ($relations as $name => $relation) {
dump($name);
foreach ($relation as $relationRecord) {
$newRelationship = $relationRecord->replicate();
$newRelationship->product_id = $newProductId;
$newRelationship->push();
}
}
}
}
}