I am beginner in Laravel and php. I use in my project (Laravel 7) this component: https://packagist.org/packages/kalnoy/nestedset
I need a function to delete the selected branch (record) along with the records "deep".
I try with this code:
public function destroy(Request $request, int $parentId, int $id)
{
$node = $this->model->where('id', $id)->get();
$arrayToDelete = array();
$traverse = function ($categories) use (&$traverse, &$arrayToDelete) {
foreach ($categories as $category) {
$arrayToDelete[] = $category->id;
$traverse($category->children);
}
};
$traverse($node);
foreach ($arrayToDelete as $value) {
$this->model->where('id',$value)->delete();
}
return redirect()->route('subcategory.index', ['id' => $id, 'parentId' => $parentId])->with('success', 'Rekord usunięty poprawnie');
}
but I have error:
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (
cms
.products
, CONSTRAINTproducts_category_id_foreign
FOREIGN KEY (category_id
) REFERENCEScategories
(id
)) (SQL: delete fromcategories
whereid
= 1)
My migration file:
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('category_name', 155);
$table->string('description', 155)->nullable();
$table->string('keywords', 155)->nullable();
$table->longText('content')->nullable();
$table->char('enable', 1)->default(0);
$table->string('photo', 155)->nullable();
$table->bigInteger('order')->default(0);
$table->string('slug', 160)->nullable();
NestedSet::columns($table);
$table->engine = "InnoDB";
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_unicode_ci';
})
In manual: https://packagist.org/packages/kalnoy/nestedset
I found this:
Deleting nodes To delete a node:
$node->delete(); IMPORTANT! Any descendant that node has will also be deleted!
IMPORTANT! Nodes are required to be deleted as models, don't try do delete them using a query like so:
Category::where('id', '=', $id)->delete();
How should I change my code to. did the deletion work correctly?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire