简体   繁体   中英

Check if value exists in MySQL table and then select [Laravel 5]

Here is my pivot table project_group :

+-----+----------+------------+----------+---------+
| ids | group_id | project_id | admin_id | user_id |
+-----+----------+------------+----------+---------+
|   4 |      115 |          1 |        1 | [3,4,5] |
|   5 |      115 |          2 |        1 | [5,2,1] |
|   6 |      115 |          3 |        1 | [1,3,6] |

This table represent group linked to the projects.... user_id is which users can see projects/group... Is there any way to display correct projects/group only to the users defined in user_id ?

Also content in user_id field can be changed....

The best way to handle this would be to first normalize your database. Storing comma separated lists in a cell is allowed, but generally bad practice, as explained in this question .

If you can have multiple users per project, you should have a linking table with a column for project and a column for user, like this:

project_users:
| project_id | user_id |

and you can make (project_id, user_id) a composite primary key.

That way, you can select the users for a project (say, project 1) like this:

SELECT user_id
FROM project_users
WHERE project_id = 1;

Once you have these, you can display the project data only to users whose id is returned in the above list.

I have built an SQL Fiddle that helps demonstrate this visually, if it helps.

It is good to note that this proper normalization gives the opportunity to a lot of useful data as well, as it becomes easier to search for users by project, but also you can search for project information based on a user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM