当我使用以下语法删除一行时:
$user->delete();
是否有一种方法来附加一个类型的回调,这样它就会自动这样做:
$this->photo()->delete();
最好是在模型类内部。
当我使用以下语法删除一行时:
$user->delete();
是否有一种方法来附加一个类型的回调,这样它就会自动这样做:
$this->photo()->delete();
最好是在模型类内部。
当前回答
在想要删除的模型上添加删除功能 定义模型的关系
例如在这个例子中:
/**
* @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 5.2中,文档声明这些类型的事件处理程序应该在AppServiceProvider中注册:
<?php
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
User::deleting(function ($user) {
$user->photos()->delete();
});
}
我甚至打算将它们移动到单独的类中,而不是闭包中,以获得更好的应用程序结构。
我相信这是Eloquent事件(http://laravel.com/docs/eloquent#model-events)的一个完美用例。你可以使用"deleting"事件来进行清理:
class User extends Eloquent { public function photos() { return $this->has_many('Photo'); } // this is a recommended way to declare event handlers public static function boot() { parent::boot(); static::deleting(function($user) { // before delete() method call this $user->photos()->delete(); // do the rest of the cleanup... }); } } You should probably also put the whole thing inside a transaction, to ensure the referential integrity..
用户模型中的关系:
public function photos()
{
return $this->hasMany('Photo');
}
删除相关记录:
$user = User::find($id);
// delete related
$user->photos()->delete();
$user->delete();
使用限制()
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');
有3种方法可以解决这个问题:
1. 在模型引导上使用雄辩事件(参考:https://laravel.com/docs/5.7/eloquent#events)
class User extends Eloquent
{
public static function boot() {
parent::boot();
static::deleting(function($user) {
$user->photos()->delete();
});
}
}
2. 使用雄辩的事件观察者(参考:https://laravel.com/docs/5.7/eloquent#observers)
在你的AppServiceProvider中,像这样注册观察者:
public function boot()
{
User::observe(UserObserver::class);
}
接下来,添加一个Observer类,如下所示:
class UserObserver
{
public function deleting(User $user)
{
$user->photos()->delete();
}
}
3.使用外键约束(参考:https://laravel.com/docs/5.7/migrations#foreign-key-constraints)
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');