sql - cannot delete parent with children existing Laravel CRUD -


this error thrown when try delete categories entry products under parent category:

illuminate \ database \ queryexception sqlstate[23000]: integrity constraint violation: 1451 cannot delete or update parent     row: foreign key constraint fails (`store`.`products`, constraint     `products_category_id_foreign` foreign key (`category_id`) references `categories` (`id`))    (sql: delete `categories` `id` = 1) 

after did research know cannot delete parent existing children

i not sure how join products category id when delete category id. way can delete products associated category id.

here function deleting:

public function postdestroy() {     $category = category::find(input::get('id'));      if ($category) {         $category->delete();         return redirect::to('admin/categories/index')             ->with('message', 'category deleted');     }      return redirect::to('admin/categories/index')         ->with('message', 'something went wrong, please try again');  }  

if want delete products have same category, change category class extends eloquent this:

class category extends eloquent {     // ... existing code...     public function delete()     {         // delete of products have same ids...         products::where("category_id", $this->id)->delete();          // finally, delete category...         return parent::delete();     } } 

now calling $category->delete() delete products have same category_id, category itself.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -