dwijitsolutions / laraadmin

LaraAdmin is a Open source Laravel Admin Panel / CMS which can be used as Admin Backend, Data Management Tool or CRM boilerplate for Laravel with features like Advanced CRUD Generation, Module Manager, Backups and many more.
http://laraadmin.com
MIT License
1.58k stars 537 forks source link

SQL: Can't DROP <foreign-key-name> on alter table <table-name>` drop foreign key `<foreign-key-name>` #277

Open mohammad-anas opened 6 years ago

mohammad-anas commented 6 years ago

Hi, First thanks for your great effort in making such wonderful opensource tool. Recently I tried laraadmin and found an issue. While changing table for a drop down type field for a module using admin account an error occurs and giving following error SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'transaction_details_item_id_foreign'; check that column/key exists (SQL: alter table transaction_details drop foreign key transaction_details_item_id_foreign) I am giving exact error from my code.

This error occurred due to following code in class Dwij\Laraadmin\Models\Module (at line 317, may be other line if code changed) $table->dropForeign($field->module_obj->namedb."".$field->colname."_foreign");

Issue is due to non-existence of the foreign key which is not checked whether exists or not.

So I tried a solution as below

1. Add a new method to check existence of foreign key public static function hasForeignKey($tableName, $foreignKey){ $foreignKeyIndex=DB::select("SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = ? AND CONSTRAINT_NAME=?", [$tableName, $foreignKey]); if(!is_null($foreignKeyIndex) && !empty($foreignKeyIndex)){ return true; }else{ return false; } }

2. Check that foreign key exists and only then delete if(Module::hasForeignKey($table->getTable(), $field->module_obj->namedb."".$field->colname."_foreign")){ $table->dropForeign($field->module_obj->namedb."".$field->colname."_foreign"); }

If you guys resolve it in another way please resolve.

Thanks

theamanchoudhary commented 6 years ago

It really helps thank you.

leopinzon commented 6 years ago

I'd suggest uploading this fix to the repo! :) Thanks a lot