3 回答

TA貢獻1776條經驗 獲得超12個贊
如果要在刪除記錄時始終刪除所有子關系,可以在模型的 boot 函數中的刪除方法中進行。像這樣的東西:
供應商模型
class Vendor extends Model
{
public static function boot() {
parent::boot();
// when you are deleting a Vendor, also delete all related brands
static::deleting(function($vendor){
$vendor->brands->each(function($brand) {
$brand->delete();
});
});
}
protected $hidden = ['created_at','updated_at'];
public function brands(){
return $this->hasMany(Brand::class);
}
}
品牌型號
class Brand extends Model
{
public static function boot() {
parent::boot();
// when you are deleting a Brand, also delete all related products
static::deleting(function($brand){
$brand->products->each(function($product) {
$product->delete();
});
});
}
public function vendor() {
return $this->belongsTo(Vendor::class);
}
public function products() {
return $this->hasMany(Product::class);
}
}
產品型號
class Product extends Products
{
public static function boot() {
parent::boot();
// when you are deleting a Product, also delete/detach all you need
static::deleting(function($product){
/*
$product->sizes()->detach();
$product->tags()->detach();
$product->fields()->detach();
$product->countries()->detach();
$product->exportationFactors->each(function($exportationFactor) {
$exportationFactor->delete();
});
*/
});
}
public function brand()
{
return $this->belongsTo(Brand::class);
}
}
然后在您的控制器中刪除與每個控制器對應的記錄。
供應商銷毀功能
public function destroy($id)
{
DB::beginTransaction();
Vendor::findOrFail($id)->delete();
DB::commit();
}
品牌破壞功能
public function destroy($id)
{
DB::beginTransaction();
Brand::findOrFail($id)->delete();
DB::commit();
}
產品銷毀功能
public function destroy($id)
{
$product = Product::findOrFail($id);
DB::beginTransaction();
$this->removeProductImage($product);
$product->delete();
DB::commit();
}

TA貢獻1846條經驗 獲得超7個贊
添加你擁有的onDelete('cascade')
每一個$table->foreign('<Column>')
。
例子:
$table->foreign('vendor_id')->references('id')->on('vendors')->onDelete('cascade');
然后不需要先刪除所有的孩子,只需刪除父母。

TA貢獻1775條經驗 獲得超8個贊
您遇到的問題在產品表中,有兩種方法可以解決此問題:
解決方案1:
就像 Yovi 的回答狀態一樣,您可以簡單地onDelete('cascade')在您的品牌和產品表中添加您的外鍵。
品牌表:
$table->foreign('vendor_id')->references('id')->on('vendors')->onDelete('cascade');
產品表:
$table->foreign('brand_id')->references('id')->on('brands')->onDelete('cascade');
然后您的控制器銷毀方法應如下所示:供應商銷毀功能:
public function destroy($id)
{
$vendor = Vendor::findOrFail($id);
$vendor->delete();
}
品牌銷毀方法:
public function destroy($id)
{
$brand= Brand::findOrFail($id);
$brand->delete();
}
解決方案2:
如果你想手動刪除你的行,你只是在你的銷毀方法上設置了錯誤的順序。您必須首先從產品 -> 品牌 -> 供應商開始刪除最小的孩子。您的方法應如下所示:
供應商銷毀功能:
public function destroy($id)
{
DB::beginTransaction();
$vendor = Vendor::findOrFail($id);
foreach($vendor->brands() as $brand){
$brand->products()->delete();
}
$vendor->brands()->delete();
$vendor->delete();
DB::commit();
}
品牌銷毀功能:
public function destroy($id)
{
DB::beginTransaction();
$brand= Brand::findOrFail($id);
$brand->products()->delete();
$brand->delete();
DB::commit();
}
總的來說,我發現解決方案 1 更清潔。
- 3 回答
- 0 關注
- 228 瀏覽
添加回答
舉報