azem loka
azem loka

Reputation: 13

How can i delete from the multi table with fk constraint?

Ok, let's say i have 2 tables.

tbl_1

1.id_tbl1 (primary key)

2.name


tbl_2

1.id_tbl2 (primary key)

2.id_tbl1 (foreign key)

3.name


P.S If i want to delete data tbl_1 then the id_tbl1 as fk will also be deleted in tbl_2 ... *how can work with php?

Upvotes: 0

Views: 61

Answers (1)

The Impaler
The Impaler

Reputation: 48850

You need to use ON DELETE CASCADE when defining the foreign key. See below:

create table tbl_1 (
  id_tbl1 int primary key not null,
  name varchar(10)
);

create table tbl_2 (
  id_tbl2 int primary key not null,
  id_tbl1 int,
  constraint fk1 foreign key (id_tbl1) 
    references tbl_1 (id_tbl1) on delete cascade
);

See running example at DB Fiddle.

Upvotes: 2

Related Questions