[英]How to get unique record by multi-attributes
I have a model like this: Order(id: integer, user_id: integer, target_id: integer, content: string, created_at: datetime, updated_at: datetime) 我有一个这样的模型:Order(id:整数,user_id:整数,target_id:整数,内容:字符串,created_at:日期时间,Updated_at:日期时间)
It belongs to User. 它属于User。 User can make order for each other like: 用户可以像这样相互订购:
=> The unique record should be A -> B, so how can I filter Order to unique record ? =>唯一记录应为A-> B,那么如何将Order过滤为唯一记录?
Okay, assuming you have users A and B, you should just be able to do this: 好的,假设您有用户A和B,则应该能够执行以下操作:
Order.where(user: A, target: B)
...assuming you've defined your associations, otherwise: ...假设您已经定义了关联,否则:
Order.where(user_id: A.id, target_id: B.id)
EDIT: just saw your comment. 编辑:刚刚看到您的评论。 You could add .first
to either of the above queries just to get the first order if you wanted to. 您可以将.first
添加到上述任一查询中,以获取第一订单。
ANOTHER EDIT: As I understand it, if there's ever been one or more orders between A and B (or B and A), you want to grab one of them, and you don't care which. 另一个编辑:据我了解,如果A和B(或B和A)之间曾经有一个或多个订单,那么您想抓住其中一个,而不必在意。 You could do this: 您可以这样做:
(Order.where(user: A, target: B) + Order.where(user: B, target: A)).first
That will give you a record if one exists and nil
if it doesn't. 如果有一个记录,它将为您提供一条记录,如果不存在,则nil
。 Raw SQL would be more efficient: 原始SQL将更有效:
Order.where("user_id = ? AND target_id = ? OR user_id = ? AND target_id = ?", A.id, B.id, B.id, A.id).first
... but less readable, and be sure to test it. ...但是可读性较差,请务必对其进行测试。 Good luck! 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.