且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel Eloquent ORM - 多对多删除剩余的数据透视表值

更新时间:2022-12-30 20:54:04

detach 方法用于从数据透视表中释放关系,而 delete 将删除模型记录本身,即评论表中的记录.我的理解是删除不会隐式触发分离.不过,您可以使用 模型事件 来触发数据透视表的清理,例如:>

The detach method is used to release a relationship from the pivot table, whilst delete will delete the model record itself i.e. the record in the reviews table. My understanding is that delete won't trigger the detach implicitly. You can use model events to trigger a cleanup of the pivot table, though, using something like:

Review::deleting(function($review)
{
    $review->product()->detach()
}

另外,我建议这种关系是一对多的,因为一个产品会有很多评论,但一个评论不会属于很多产品(通常).

Also, I would suggest that the relationship would be a one to many, as one product would have many reviews, but one review wouldn't belong to many products (usually).

class Review extends Eloquent {
    public function product()
    {
        return $this->belongsTo('Product');
    }
}

class Product extends Eloquent {
    public function reviews()
    {
        return $this->hasMany('Review');
    }
}

当然,这需要您调整数据库结构.如果您想保留数据库结构和您当前的关系,另一种选择是在数据透视表上应用外键约束,这样当评论或产品被删除时,您可以级联删除数据透视表.

Of course, this would then require that you tweak your database structure. If you wanted to leave the database structure and your current relationships as they are, the other option would be to apply a foreign key constraint on the pivot table, such that when either a review or product is removed, you could cascade the delete on the pivot table.

// Part of a database migration
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('review_id')->references('id')->on('reviews')->onDelete('cascade');

在添加约束时,您将清理工作推送到数据库上,而不必担心在代码中处理它.

In adding the constraint, you push the cleanup work onto the database, and don't have to worry about handling it in code.