简体   繁体   中英

Mysql tables relationships

In Laravel I have the following table pseudo layout:

Table Comments belongs to table Image {an Image can have many Comments, each comment has an image id}

Table Image belongs to table Collections {a Collection can have many Images, each image has a collection id}

Table Collection belongs to table User {a User can have many Collections, each collection has a user id}

How do I list all Comments belonging to a given User? I guess I could add the user id in the Comments table, but that seems kind of clumsy. If anyone knows how to do this in Laravel, that would be great. Or maybe a Mysql query hinting at the solution... I need to get an idea where to start.

Thank you

Can't help with Laravel, but if it were SQL this is what I would do. Of course, this is assuming that your User table follows the pattern of your other tables. If this is wrong, it would help if you posted your table layouts, and I can try again.

SELECT Com.Comment
FROM Collection Col
  INNER JOIN Image I
    ON I.Collection_Id = I.Collection_Id
  INNER JOIN Comments Com
    ON Com.Image_Id = I.Image_Id
WHERE Col.User_Id = {User_Id} -- however it is that you represent the variable

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