简体   繁体   中英

Delete Data From all tables using Load() Laravel 5.5

i am trying to delete Model from Model table and all of its comments from Comments table...my current code delete the model but not its comments from the other table...

Here is my destroy function

public function destroy(Request $request,CadModel $cadmodel)
    {
        $cadmodel->load('comments')->delete();
        $request->session()->flash('message.level', 'success');
        $request->session()->flash('message.content', 'File Deleted Successfully!');
        return redirect()->route('dashboard');
    }

Here is the relationship i defined in CadModel Laravel Model...

 public function comments()
    {
        return $this->hasMany(Comment::class);
    }

Please Reply and suggest me a solution to delete both..Model and its Comments

In your migration, set your related comments to be deleted if the model is deleted with onDelete('cascade') .

Example:

/**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
        Schema::create('comments_model', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('comment_id')->unsigned();
            $table->integer('model_id')->unsigned();

            $table->foreign('comment_id')->references('id')->on('comments')->onDelete('cascade');
            $table->foreign('model_id')->references('id')->on('models')->onDelete('cascade');
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM