mysql structure for posts and comments

后端 未结 1 1972
没有蜡笔的小新
没有蜡笔的小新 2021-01-07 10:10

I\'ve read several tutorials, documentations about mysql, db structures and also I\'m using it via php for weeks. Now I get a problem, I don\'t know how to form/organize/cre

相关标签:
1条回答
  • 2021-01-07 10:34

    At a basic level, you would have a table for each type of "thing" in your application. In this case, a table for Posts and a table for Comments. Something as simple as this:

    Post
    --------
    Id
    Content
    User
    DatePosted
    
    Comment
    --------
    Id
    PostId
    Content
    User
    DatePosted
    

    This would create what's called a one-to-many (or zero-to-many, actually) relationship between Posts and Comments, whereby each Post can have zero or more associated Pomments but each Comment can be associated with only one Post.

    In your code (which is a whole other subject entirely), to display a Post and its associated Comments there are a couple of things you could do. Assuming you have, as input, the Id of the Post you want, you can get that Post and its Comments:

    SELECT `Content`, `User`, `DatePosted` FROM `Post` WHERE `Id` = ?Id
    SELECT `Id`, `Content`, `User`, `DatePosted` FROM `Comment` WHERE `PostId` = ?Id
    

    What you do with that resulting data is up to you and how you want to use it in your application. It would come back as two table results, the former of which has one record (if the Post exists) and the latter of which has zero or more records. Naturally, you'll want to check that things exist before trying to use them, etc. (So if the first query returns no results, don't try to continue to display the Post. Just show a default response or an error.)

    0 讨论(0)
提交回复
热议问题