【问题标题】:Delete second level of belonging in Eloquent删除 Eloquent 中的第二层归属感
【发布时间】:2019-02-24 14:41:55
【问题描述】:

我的应用程序有一个Category 模型。每个Category 可以有多个Subcategories,所以每个Subcategory belongsTo 一个Category。来自Subcategory 模型:

public function category()
{
    return $this->belongsTo('App\Category');
}

另一方面,有一个Friend 模型。现在,每个 Friend/Subcategory 对都通过枢轴 friend_score 表连接:

id | friend_id | subcategory_id | score

来自Subcategory 模型:

/**
 * The friend scores that belong to the subcategory.
 */
public function friends()
{
    return $this->belongsToMany('App\Friend', 'friend_score')->withPivot('score');
}

来自Friend 模型:

/**
 * The subcategory scores that belong to the friend.
 */
public function subcategories()
{
    return $this->belongsToMany('App\Subcategory', 'friend_score')->withPivot('score');
}

当我删除一个子类别时,Eloquent 会自动且正确地从friend_score 表中删除该subcategory_id 的条目。

当我删除一个类别时,它会正确删除属于该category_id 的子类别。但是,在这种情况下,相关的friend_scores 仍保留在数据库中。

删除类别时如何使其删除每个子子类别的friend_score?

我知道我可以手动遍历它们并删除它们,但我想知道是否有办法通过模型关系自动实现这一点。

【问题讨论】:

  • 你能显示子类别表结构吗?
  • @TeomanTıngır 这只是id | category_id | name | created_at | updated_at

标签: laravel eloquent


【解决方案1】:

在您的friend_score 迁移中,您可以将 subcategory_id 定义为外键。然后您可以选择删除子类别时使用onDelete() 方法对记录进行透视。

$table->foreign('subcategory_id')
      ->references('id')
      ->on('subcategories')
      ->onDelete('cascade');

使用级联选项,当子类别被删除时,所有相关的pivot记录都将被删除..

所以当你删除一个类别时,删除会通过子类别冒泡给好友分数

category-> subcategory -> 好友分数(枢轴)

【讨论】:

  • 谢谢。有没有办法从模型内部完成相同的任务,而不是通过迁移?
  • @jovan 好吧,您可以手动删除,但需要额外的查询。为什么不让数据库来处理呢?
【解决方案2】:

您可以更新迁移并添加onDelete() 级联,这将是我处理此类情况的首选方式。但如果你真的想手动执行此操作,可以使用 eloquent 的事件,如下所示:

Subcategory模特:

/**
 * Boot eloquent model events
 * 
 * @return void
 */
public static function boot() {

    parent::boot();

    // This will be called just before deleting a
    // subcategory entry

    static::deleting(function($subcategory) {

        Friend::where('subcategory_id', $subcategory->id)->delete();
    });
}

在做任何事情之前,您可以通过以下方式进行清理:

Friend::whereDoesntHave('subcategories')->get();

检查上面是否返回与子类别表没有任何关系的条目的正确结果。然后你可以调用->delete()而不是->get()来清理朋友模型条目。

【讨论】:

    猜你喜欢
    • 2018-05-22
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多