且构网

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

Laravel雄辩ORM - 多对多删除数据透视表值

更新时间:2022-12-30 21:17:18

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

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');
    }
}

当然,这将要求您调整数据库结构如果你想离开数据库结构和你的c另外一个选择是将外键约束应用到数据透视表上,这样当查看或产品被删除时,您可以在数据透视表上级联删除。

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.