sqlalchemy orm-最新消息的最新线程

jm81lzqq  于 2021-07-26  发布在  Java
关注(0)|答案(0)|浏览(150)

我正在尝试按最新消息列出消息线程。结构分为三个表:

message_threads
--id (int)
--title (string)

messages
--id (int)
--text (string)
--timestamp (datetime)

message_thread_subscriptions
--user_id (int)
--thread_id (int)
--other_fields (...)

我试着这样使用backref,但我想我误解了它们的用法:

thread = relationship("MessageThread", backref=backref("messages", lazy="dynamic"), order_by="Message.timestamp.asc()")

现在我有了下面的sql查询,虽然我不确定它是否是最有效的(这里是SQLFIDLE):

SELECT *
FROM message_thread_subscriptions
 JOIN (
   SELECT thread_id, message, max(timestamp) FROM messages GROUP BY thread_id
 ) AS latest_messages
  ON message_thread_subscriptions.thread_id = latest_messages.thread_id 
 JOIN message_threads
  ON message_thread_subscriptions.thread_id = message_threads.id AND message_thread_subscriptions.user_id=?

然而,我失去了将其转换为orm的sqlalchemy。我尝试了这个方法,但是我不确定如何访问结果(因为它们在不同的对象上),并且我得到一个错误,即没有这样的列消息。线程\u id:

latest_messages = session.query(Message.thread_id, Message.author_id, Message.text,
                func.max(Message.timestamp).label("latest_timestamp")).group_by(
                Message.thread_id
                ).subquery()
query = session.query(MessageThreadSubscription).join(
    latest_messages, and_(
        Message.thread_id == MessageThreadSubscription.thread_id,
        MessageThreadSubscription.user_id == context.user_id
    )
).join(
    MessageThread, MessageThreadSubscription.thread_id == MessageThread.id
)

非常感谢您的帮助:)

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题