In my project, I’ve two Tables in Database 1st is my tickets table where tickets data is stored. and 2nd is gp_group where tickets ID is stored in gpid from tickets id. See the below image :- Tickets table
and whenever I Delete a ticket then I have to delete ticket data from both tickets table and gp_group table for that ticket. See the below image :-gp_group table
Now, My problem is that I am not able to delete the ticket data from gp_group table but tickets table data is deleted.
So, I’ve used a function in my delete function to delete the data from both the table when I delete the ticket. But still not work.
Code in TicketController
public function destroy(Ticket $ticket)
{
$ticket =DB::table('tickets')
-> leftJoin('gp_group','tickets.id', '=','gp_group.ticket_id')
-> where('tickets.id',$ticket);
DB::table('gp_group')->where('ticket_id',$ticket)->delete();
$ticket->delete();
return redirect()->route('tickets.index')
->with('success','Group deleted successfully');
}
I get this error "Object of class Illuminate\Database\Query\Builder could not be converted to string"
And trying other code in function
public function destroy(Ticket $ticket)
{
$ticket->delete();
ticket::where("id", $ticket)->delete();
gp_group::where("gpid", $ticket)->delete();
return redirect()->route('tickets.index')
->with('success','Group deleted successfully');
}
But still not work.
i get different error "SQLSTATE[42S02]: Base table or view not found: 1146 Table 'rp1.gp_groups' doesn't exist (SQL: delete from gp_groups
where gpid
= {"id":63,"gpname":"Nasser","detail":"Nasser","gender":"Male","semester":432,"status":"Not assigned","Assigned":null,"user_id":1,"track_id":5,"created_at":"2021-10-15T18:50:04.000000Z","updated_at":"2021-10-15T18:50:04.000000Z"})"
I would be very thankful if anyone could point-out mistake I'm doing here.
CodePudding user response:
To do this you will need to create in your table a foreign key to delete on cascade
:
And then you can delete the parent registry (tickets
table) and with that automatically will delete all items with the reference in the gp_group
table the registries of the other table.
CodePudding user response:
Quick solve to your issue, you need to pass only the Id to the where function Not the whole ticket like this
-> where('tickets.id',$ticket->id);
here is the full updated function
{
$ticket->delete();
gp_group::where("gpid", $ticket->id)->delete();
return redirect()->route('tickets.index')
->with('success','Group deleted successfully');
}
and you may consider foreign keys for that task, it will delete the gp_group
record automatically whenever its ticket is deleted
read more about it here