Home > other >  How to delete data with foreign key?(solved)
How to delete data with foreign key?(solved)

Time:10-04

I need some help to delete a movie from my database.

I know that since I have pivot tables I will get some troubles with foreign key(my delete controller gives this error), but I don't know how to solve it.

The error i'm getting is the following: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (sakila.film_category, CONSTRAINT fk_film_category_film FOREIGN KEY (film_id) REFERENCES film (film_id) ON UPDATE CASCADE) (SQL: delete from film where film_id = 999)

My database tables

Here are my models:

model Film:

class film extends Model{
    protected $table = "film";  
    protected $primaryKey = 'film_id';
    public $timestamps = false;
    use HasFactory;
    protected $sql=['film_id', 'title', 'length'];

    public function category(){
        return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id');
    }        
    public function actor(){
              return $this->belongsToMany(actor::class,'film_actor', 'film_id', 'actor_id');
    }    
} 

model Category:

class category extends Model{
    protected $table = "category";
    protected $primaryKey = 'category_id';
    public $timestamps = false;
    use HasFactory;
    protected $sql=['category_id','name'];

    public function film(){
        return $this->belongsToMany(film::class,'film_category', 'category_id', 'film_id');
    }
}

model Actor:

class actor extends Model{
    protected $primaryKey = 'actor_id';
    public $timestamps = false;
    use HasFactory;
    protected $sql=['actor_id', 'first_name', 'last_name'];

    public function film(){
          return $this->belongsToMany(film::class,'film_actor', 'actor_id', 'film_id');
      }
}

Now I need some help to make my controller function to delete records.

 public function remove($film_id){
        $film=film::findOrFail($film_id);
        $film->delete();
        
        return redirect('/film/view');

Thanks

CodePudding user response:

To delete a movie, you must first delete the records from the Film_category and Film_actor table before you can delete your record from the Film table.

Instead do something like :

(assuming you have created your models from the Film_category and Film_actor tables)

public function remove($film_id){

    $film_category = FilmCategory::where('film_id', $film_id)->delete();
    $film_actor = FilmActor::where('film_id', $film_id)->delete();
    
    $film = film::findOrFail($film_id);
    $film->delete();
            
    return redirect('/film/view');
  
}
  • Related