Laravel关于删除对象的调用模型事件-已删除

时间:2018-07-09 08:40:50

标签: php laravel laravel-5 model relational-database

我正在尝试调用模型事件-已删除。当我删除视频时,我还希望删除与视频相关的所有评论,这一切正常。但是我也有供稿表,当我删除视频时,我也要删除所有评论和评论供稿。现在,当我删除视频时,我将删除-视频,视频评论,视频供稿,但我还需要删除视频评论供稿。

问题是,当我删除视频时,如何才能删除评论供稿? 检查VideoController.php销毁功能

Video.php-模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;

class Video extends Model
{

    protected $table = 'videos';
    public $timestamps = false;
    use Sluggable, RecordsFeed;

    public static function boot()
    {
        parent::boot();
    }

    public function sluggable()
    {
      return [
          'slug' => [
              'source' => 'title'
          ]
        ];
    }

    public function comments()
    {
      return $this->hasMany('App\VideoComment', 'videoid', 'id');
    }

    public function member()
    {
      return $this->belongsTo('App\Member', 'userid', 'member_id');
    }

}

VideoComments.php-模型

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class VideoComment extends Model
{
    protected $table = 'videos_comments';
    public $timestamps = false;
    protected $fillable = [
      'text', 'userid', 'date'
    ];
    use RecordsFeed;

    public function videos() {
      return $this->belongsTo('App\Video', 'id', 'videoid');
    }
    public function member() {
      return $this->belongsTo('App\Member', 'userid', 'member_id');
    }
}

RecordsFeed.php

    <?php

namespace App;
use App\Libraries\Portal;

trait RecordsFeed
{

    protected static function bootRecordsFeed() {

        static::created(function($model) {
            $model->recordFeed('created');
        });

        static::deleted(function($model) {
            $model->deleteFeed('deleted');
        });

    }

    public function feeds() {
        return $this->morphMany( Feed::class, 'feedable' );
    }

    protected function recordFeed($event) {
        $this->feeds()->create([
            'user_id' => (new Portal)->getMemberID(),
            'type' => $event.'_'.strtolower(class_basename($this))
        ]);
    }

    protected function deleteFeed($event) {
        $this->feeds()->delete();
    }

}

VideoController.php销毁功能

public function destroy($id)
{
    $video = Video::findOrFail($id);
    $video->comments()->delete();
    $video->delete();

    Session::flash('success', 'Video deleted');
    return redirect()->route('video.index');
}

2 个答案:

答案 0 :(得分:1)

为什么在创建表时不使用删除级联?

在迁移中,创建外键时,只需指定on delete动作,如下所示:

$table->foreign('your_key')->references('id')->on('your_table')->onDelete('cascade');

它将自动删除与父对象关联的行。

您可以在here的Laravel文档中找到更多详细信息。

答案 1 :(得分:0)

您无需执行任何代码,可以在数据库中进行设置,并可以使用relationshiop在级联上设置删除。