简体   繁体   中英

delete with eager load in laravel

I'm trying to delete a collection but I want to delete the NFTs related to a collection as well. How do I do this?

This is my Nft model Nft.php

class Nft extends Model
{
    use HasFactory,SoftDeletes;

    public function collection()
    {
        return $this->belongsTo(Collection::class);
    }
}

This is my collection model Collection.php

class Collection extends Model
{
    use HasFactory, SoftDeletes;
    public function nfts()
    {
        return $this->hasMany(Nft::class);
    }
}

This is my COntroller CollectionController.php

 public function deleteCollection(int $id):RedirectResponse
    {
        Collection::with('nfts')->find($id)->delete();
        return redirect('/collections');
    }

But it did not work!!! pleas help me!!!!!

At user model:

public function collection() {
return $this->belongsTo(Collection::class)->withTrashed(); }

Keep in mind that the observer events are not fired if you use mass delete for example. In the case Collection::with('nfts')->delete(); it might not work.

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Collection extends Model
{
    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::deleting(function ($collection) {
            $collection->nfts()->delete()
        });
    }
}

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