ops
ops

Reputation: 2049

mysql self relationship with 2 field

I have user table like this:

  id          email
-------------------------
  1       [email protected]

And menu table like this:

  id   parent_id   user_id   name
-----------------------------------
  1       NULL        1      tets

I would like to self relationship parent_id AND user_id.
If hacker wanna to add this record mysql ignored this action, Because user_id 2 not owner parent menu 1!!! :

  id   parent_id   user_id   name
-----------------------------------
  2       1           2      tets

Upvotes: 1

Views: 80

Answers (1)

Andrews B Anthony
Andrews B Anthony

Reputation: 1381

1.create table User using below query

create table User(id int primary key,email varchar(30));

2.create table Menu using the below query

create table Menu(id,int,u_id int,p_id int,name varchar(10),primary key(u_id,p_id),
    constraint user_fk foreign key(id) references User(id) 
      on delete cascade);

when you enter a value which is not present in the table User then below error will be thrown

Cannot add or update a child row: a foreign key constraint fails

Upvotes: 1

Related Questions