【问题标题】:on cascade delete on many to many relationship in laravel关于 laravel 中多对多关系的级联删除
【发布时间】:2019-03-23 02:40:13
【问题描述】:

我使用了多对多关系。我有三个名为:product、tag、productstag 的表。在这里,我希望每当我要删除一个产品时,它也会删除它在 productstag 表上的关系。

public function up()
{
    Schema::create('productstags', function (Blueprint $table) {
        $table->integer('product_id');
        $table->integer('tag_id');
        $table->primary(['product_id','tag_id']);
        $table->timestamps();
    });
}

如您所见,我使用 product_id 和 tag_id 作为主键。 所以我不能用这个

$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('tag_id')->references('id')->on('products')->onDelete('cascade');

那还有什么办法呢?

在我的产品模型上

 public function tags()
{
    return $this->belongsToMany('App\Tag','productstags','product_id','tag_id')->withTimestamps();


}

在我的标签模型上:

public function products()
{
    return $this->belongsToMany('App\Product','Productstags','tag_id','product_id');

}

关于我的产品销毁功能:

public function destroy(Request $request,$id)
{
    $product=Product::findOrFail($id);
    if($request->file('image')==''){
        $input=$request->except('photo_id');
    }
    else{
        $input=$request->all();
        unlink(public_path()."/images/".$product->image->name);

    }

    $product->delete($input);
    Session::flash('deleted_user','the user has been deleted');

    return  redirect(route('product.index'));

}

【问题讨论】:

  • product_idtag_idprimary key 是否有特定原因?
  • 是的! @AlbertoGuilherme

标签: laravel many-to-many


【解决方案1】:

它不如cascade 漂亮,但你可以重写 delete 方法并这样做:

public function delete(){
    $this->name_of_the_relationship()->delete();
    return parent::delete();
}

【讨论】:

  • 感谢您的回复!我已将该功能放在我的 productstags 迁移表上。但是当我删除一个产品时,它仍然没有从 productstags 表中删除。我应该把那个功能放在哪里?
  • @JubayerAhmed - 该功能适用​​于产品model。有关系的类
  • 我没有产品标签模型也没有功能。正如我之前提到的,这是多对多的关系!我迁移表 .productstags 是数据透视表。
  • @JubayerAhmed 你有什么型号? delete函数怎么调用?
  • 我有产品模型和标签模型。 productstags 是数据透视表。在产品型号上我有标签功能。当我删除产品时,它会通过 ProductController@destroy menthod 删除它。
猜你喜欢
  • 2013-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-11
  • 1970-01-01
  • 1970-01-01
  • 2018-06-28
  • 2016-05-03
相关资源
最近更新 更多