当我使用以下语法删除一行时:
$user->delete();
是否有一种方法来附加一个类型的回调,这样它就会自动这样做:
$this->photo()->delete();
最好是在模型类内部。
当我使用以下语法删除一行时:
$user->delete();
是否有一种方法来附加一个类型的回调,这样它就会自动这样做:
$this->photo()->delete();
最好是在模型类内部。
当前回答
我在《Laravel 8》中使用了这种方法:
public static function boot() {
parent::boot();
static::deleted(function($item){
$item->deleted_by = \Auth::id(); // to know who delete item, you can delete this row
$item->save(); // to know who delete item, you can delete this row
foreach ($item->photos as $photo){
$photo->delete();
}
});
}
public function photos()
{
return $this->hasMany('App\Models\Photos');
}
注意:在此语法中删除$user->photos()->delete();对我没用……
其他回答
注意:这个答案是为Laravel 3编写的。因此,在Laravel的最新版本中可能会或可能不会很好地工作。
在真正删除用户之前,您可以删除所有相关照片。
<?php
class User extends Eloquent
{
public function photos()
{
return $this->has_many('Photo');
}
public function delete()
{
// delete all related photos
$this->photos()->delete();
// as suggested by Dirk in comment,
// it's an uglier alternative, but faster
// Photo::where("user_id", $this->id)->delete()
// delete the user
return parent::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..
在定义模型迁移时最好使用onDelete级联。它负责为你删除模型的关系:
e.g.
$table->foreign(’user_id’)
->references(’id’)->on(’users’)
->onDelete(’cascade’);
如果您碰巧发现自己正在考虑如何删除一个模型及其关系到大于3或4个嵌套关系的级别,那么您应该考虑重新定义您的模型关系。
是的,但是正如@supersan在上面的评论中所说,如果你在QueryBuilder上删除(),模型事件将不会被触发,因为我们没有加载模型本身,然后在该模型上调用delete()。
只有在模型实例上使用delete函数时,才会触发事件。
所以,有人说:
if user->hasMany(post)
and if post->hasMany(tags)
为了在删除用户时删除post标签,我们必须遍历$user->个帖子,并调用$post->delete()
Foreach ($user->posts as $post) {$post->delete();} ->这将在Post上触发删除事件
VS
$user->posts()->delete() ->这将不会在post上触发删除事件,因为我们实际上没有加载post模型(我们只运行SQL: delete *从user_id = $user->id的帖子,因此,post模型甚至没有加载)
用户模型中的关系:
public function photos()
{
return $this->hasMany('Photo');
}
删除相关记录:
$user = User::find($id);
// delete related
$user->photos()->delete();
$user->delete();