V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
rogwan
V2EX  ›  Python

对文章发表评论时,怎样根据 postid,获取原文章的 user id?

  •  
  •   rogwan · 2016-01-09 23:15:14 +08:00 · 2212 次点击
    这是一个创建于 3031 天前的主题,其中的信息可能已经有所发展或是发生改变。

    数据库用 MySQL ,使用外键关联, ORM 是 Flask 里的 SQLALchemy 。

    用户表( User ): id, username
    文章表(Post): id, content
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    评论表( Comment ): id, content, post_author_id
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    comment_id = db.Column(db.Integer, db.ForeignKey('posts.id'))

    现在用户李四对用户张三发表的某一篇文章进行评论,比如:
    http://myblog.com/post/<postid>
    这个时候,我希望在存储李四对张三文章进行评论的同时,根据<postid>查出 post 的 user_id ,把该 user_id 存到 Comment 表的 post_author_id 中(就是说评论表 Comment 中,既保存了评论人李四的 id ,也保存了原文章作者张三的 id),这句 SQLALchemy 语句要怎么写呢?

    post_author_id = ?

    3 条回复    2016-01-10 02:38:47 +08:00
    kumakiti
        1
    kumakiti  
       2016-01-09 23:19:47 +08:00
    我的理解是记录评论时,在评论的 record 中记录评论作者的用户 id
    那么有文章 id ,是不是可以查询出文章的 record ,然后获取到文章作者的 id
    然后记录进评论呢?


    我也比较菜,如有大牛看出错误,欢迎指正:)
    lecher
        2
    lecher  
       2016-01-10 02:14:09 +08:00
    业务上面可以反过来做。在显示文章的时候,就把文章作者的 post_author_id 也传给前端。这样在前端提交请求的时候,就可以在同一个页面拿到文章的 post_id post_author_id, 同时提交到评论接口上处理。
    domty
        3
    domty  
       2016-01-10 02:38:47 +08:00   ❤️ 1
    搞清楚关联
    用户对应文章是一对多 一个用户可以有多个文章 每篇文章存取一个用户 id
    文章对应文章评论是一对多 一个文章可以有多个评论 每个评论保存一个文章 id
    发布评论的人对文章评论是一对多 一个人可以发布多个文章评论 每个评论记录一个评论人 id

    理论上文章作者 id 和评论人 id 是毫无关联的,没必要同时保存
    实际操作中可以报文章作者 id 信息扔到隐藏域或者变量里,发请求前获取这个变量参数即可
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5696 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 06:30 · PVG 14:30 · LAX 23:30 · JFK 02:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.