I'm trying to delete a product that has 6 relationships as follow:
- brand->belongsTo(Brand::class);
- tags->belongsToMany(Tag::class, 'tags_product');
- fields->belongsToMany(Field::class, 'product_field');
- sizes->belongsToMany(Size::class, 'product_size');
- countries->belongsToMany(Country::class, 'country_product');
- countryProducts->hasMany(CountryProduct::class);
- productFields->hasMany(ProductField::class);
- exportationFactors->hasMany(ExportationFactor::class);
Do I have to get rid of those relations first or not necessarily?
Currently I have this code for the delete function
ini_set('max_execution_time', 300);
$products = $request->all();
try {
DB::beginTransaction();
foreach ($products as $product) {
$dbProduct = $this->getProduct($product['SKU']);
$dbProduct->brand()->delete();
$dbProduct->tags()->delete();
$dbProduct->fields()->delete();
$dbProduct->sizes()->delete();
$dbProduct->countries()->delete();
$dbProduct->exportationFactors()->delete();
Log::error($dbProduct);
$dbProduct->delete();
}
DB::commit();
} catch (Exception $e) {
DB::rollBack();
throw new HttpException(500, 'Sucedio un error eliminando la información favor intentar de nuevo');
}
And I get this error
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (
sondel
.products
, CONSTRAINTproducts_brand_id_foreign
FOREIGN KEY (brand_id
) REFERENCESbrands
(id
)) (SQL: delete frombrands
wherebrands
.id
= 2)