问题描述
我想问一个问题。我正在 Laravel 8 中开发一个项目。我有 3 个表产品(id、名称)、url(id、page_id、request_id)和 product_url(product_id、url_id、site_id)。当一个产品或 url 被删除时,我可以从 product_url 表中删除它。没有问题,但是当我从product表中删除一个数据的时候,我想从product_url表中删除所有连接到那个product的url,但是没有用,虽然我在里面给了onDelete('cascade') product_url 表。 :(有没有简单的方法来实现这一目标?
产品迁移:
Schema::create('products',function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
网址迁移:
Schema::create('urls',function (Blueprint $table) {
$table->id();
$table->text('page_url');
$table->text('request_url')->nullable();
$table->timestamps();
});
Product_Url 数据透视迁移:
Schema::create('product_url',function (Blueprint $table) {
$table->foreignId('product_id')->constrained();
$table->foreignId('url_id')->constrained()->cascadeOnDelete();
$table->unsignedBigInteger('site_id');
});
产品型号:
use HasFactory;
protected $fillable = ['name'];
protected $hidden = ['created_at','updated_at'];
public function url()
{
return $this->belongsToMany(Url::class)
->withPivot('site_id');
}
public function sites()
{
return $this->belongsToMany(Site::class,'product_url')
->withPivot('product_id','url_id');
}
网址模型:
use HasFactory;
protected $fillable = ['page_url','request_url'];
protected $hidden = ['created_at','updated_at'];
public function products()
{
return $this->belongsToMany(Product::class)
->withPivot('site_id');
}
public function sites()
{
return $this->belongsToMany(Site::class,'url_id');
}
public function urls()
{
return $this->belongsToMany(self::class)
->withPivot('url_id');
}
产品控制器:
public function destroy($id)
{
$product = Product::find($id);
$product->url()->detach();
$product->delete();
return redirect()->route('product.index');
}
网址控制器:
public function destroy($id)
{
$Url = Url::find($id);
$Url->products()->detach();
$Url->delete();
return redirect()->route('url.index');
}
解决方法
要删除多对多关系记录,请使用 detach
方法。 detach
方法将从中间表中删除相应的记录;但是,这两个模型都将保留在数据库中:
//Detach a single url from product
$product->urls()->detach($urlId);
//Detach All urls from the product
$product->urls()->detach();
为了方便起见,分离也接受 ID 数组作为输入:
$product->urls()->detach([1,2,3]);
然后您可以删除您的产品模型和相关模型。
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Product $product
* @return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$product->url()->detach();
$product->url()->delete();
$product->delete();
return redirect()
->route('product.index')
->withSuccess('Product başarılı şekilde silindi.');
}
,
解决了这个问题。我用with将url添加到ProductController的destroy方法中,然后我先用$product->url()->delete()删除了关系表,然后我清除了数据透视表并从产品表中删除了产品。>
public function destroy($id)
{
$product = Product::with('url')->find($id) ?? abort(404,'Product Bulunamadı');
$product->url()->delete();
$product->url()->detach();
$product->delete();
return redirect()->route('product.index')->withSuccess('Product başarılı şekilde silindi.');
}