简体   繁体   中英

join tables and display result [Laravel 5]

I have groups table project_group pivot table questions table

groups table:

+----+--------+---------------------+---------------------+
| id | name   | updated_at          | created_at          |
+----+--------+---------------------+---------------------+
|  1 | GROUP1 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 |
|  2 | GROUP2 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 |
+----+--------+---------------------+---------------------+

pivot table project_group :

+-----+----------+------------+----------+---------+-----------+
| ids | group_id | project_id | admin_id | user_id | user_name |
+-----+----------+------------+----------+---------+-----------+
|   4 |      115 |          1 |        1 |       3 | CLIENT    |
|   5 |      115 |          2 |        1 |       3 | CLIENT    |
+-----+----------+------------+----------+---------+-----------+

questions table:

+----+----------+---------------+---------------------+---------------------+                                                                             
| id | group_id | text          | updated_at          | created_at                                                                                      
+----+----------+---------------+---------------------+---------------------+
|  1 |      115 | PRVO PITANJE? | 2015-05-03 14:29:16 | 2015-05-03 14:29:16 |
| 26 |      115 | DRUGO PITANJE? | 2015-05-06 00:44:02 | 0000-00-00 00:00:00 |
+----+----------+---------------+---------------------+---------------------+

What I want is to display something like this:

GROUP 1

PRVO PITANJE?

DRUGO PITANJE?

BUT also to check if user 3 logged from pivot table and display that just for that user. I think it should be some JOIN project_group and question table and then to put where user_id = Atuh::id()

Any solution? :)

Firstly, your id on groups ought to align with group_id on project_group , right? So, I'll assume 'GROUP1' has id of 115 and not 1 as you have it.

Secondly, how do questions relate to projects? You have group_id on questions, which seems like it should be a project id, but this isn't certain.

SELECT text
FROM questions
INNER JOIN project_group USING ( group_id )
INNER JOIN groups ON project_group . project_id = groups . id
WHERE groups . name ='GROUP1'
AND project_group . user_id =3;

Again, this will only work if you correct group_id to be a foreign key referencing id on the groups table. In this case, this should do what you want.

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