当我使用以下语法删除一行时:
$user->delete();
是否有一种方法来附加一个类型的回调,这样它就会自动这样做:
$this->photo()->delete();
最好是在模型类内部。
当我使用以下语法删除一行时:
$user->delete();
是否有一种方法来附加一个类型的回调,这样它就会自动这样做:
$this->photo()->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..
其他回答
我相信这是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..
注意:这个答案是为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();
}
}
希望能有所帮助。
在定义模型迁移时最好使用onDelete级联。它负责为你删除模型的关系:
e.g.
$table->foreign(’user_id’)
->references(’id’)->on(’users’)
->onDelete(’cascade’);
如果您碰巧发现自己正在考虑如何删除一个模型及其关系到大于3或4个嵌套关系的级别,那么您应该考虑重新定义您的模型关系。
我将遍历集合,在删除对象本身之前分离所有内容。
这里有一个例子:
try {
$user = User::findOrFail($id);
if ($user->has('photos')) {
foreach ($user->photos as $photo) {
$user->photos()->detach($photo);
}
}
$user->delete();
return 'User deleted';
} catch (Exception $e) {
dd($e);
}
我知道这不是自动的,但很简单。
另一种简单的方法是为模型提供一个方法。是这样的:
public function detach(){
try {
if ($this->has('photos')) {
foreach ($this->photos as $photo) {
$this->photos()->detach($photo);
}
}
} catch (Exception $e) {
dd($e);
}
}
然后你可以简单地在你需要的地方调用它:
$user->detach();
$user->delete();
在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();
});
}
我甚至打算将它们移动到单独的类中,而不是闭包中,以获得更好的应用程序结构。