当我使用以下语法删除一行时:
$user->delete();
是否有一种方法来附加一个类型的回调,这样它就会自动这样做:
$this->photo()->delete();
最好是在模型类内部。
当我使用以下语法删除一行时:
$user->delete();
是否有一种方法来附加一个类型的回调,这样它就会自动这样做:
$this->photo()->delete();
最好是在模型类内部。
当前回答
在定义模型迁移时最好使用onDelete级联。它负责为你删除模型的关系:
e.g.
$table->foreign(’user_id’)
->references(’id’)->on(’users’)
->onDelete(’cascade’);
如果您碰巧发现自己正在考虑如何删除一个模型及其关系到大于3或4个嵌套关系的级别,那么您应该考虑重新定义您的模型关系。
其他回答
用户模型中的关系:
public function photos()
{
return $this->hasMany('Photo');
}
删除相关记录:
$user = User::find($id);
// delete related
$user->photos()->delete();
$user->delete();
在我的情况下,这是相当简单的,因为我的数据库表是InnoDB与外键级联删除。
因此,在这种情况下,如果照片表包含用户的外键引用,那么您所要做的就是删除酒店,清理工作将由数据库完成,数据库将从数据库中删除所有照片记录。
在想要删除的模型上添加删除功能 定义模型的关系
例如在这个例子中:
/**
* @return bool|null
*/
public function delete(): ?bool
{
$this->profile()->delete();
$this->userInterests()->delete();
$this->userActivities()->delete();
$this->lastLocation()->delete();
return parent::delete();
}
用户模型中的关系为:
public function profile()
{
return $this->hasOne(Profile::class, 'user_id', 'id');
}
public function userInterests()
{
return $this->hasMany(userInterest::class, 'user_id', 'id');
}
public function userActivities()
{
return $this->hasMany(userActivity::class, 'user_id', 'id');
}
public function lastLocation()
{
return $this->hasOne(LastLocation::class, 'user_id', 'id');
}
使用限制()
Laravel 7之后,有了新的foreignId()和constrained()方法来定义数据库中的关系约束。可以在这些方法上使用OnDelete()方法自动删除相关记录。
古老的风格
$table->unsignedBigInterer('user_id');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
新风格
$table->foreignId('user_id')
->constrained()
->onDelete('cascade');
$table->foreignId('user_id')->constrained('user')->cascadeOnDelete();
or
$table->foreignId('user_id')->constrained()->cascadeOnDelete();