开发者

A complicated SQL statement

开发者 https://www.devze.com 2023-01-31 07:04 出处:网络
I have two tables. TableA -> Posts (id, title, user_id,..., created_at,..) and tableB -> Reposts (id, post_id, user_id,...created_at,...)

I have two tables.

TableA -> Posts (id, title, user_id,..., created_at,..)

and

tableB -> Reposts (id, post_id, user_id,...created_at,...)

So, in my rails app controller:

@posts = Post.find(:all, :conditions => ["use开发者_如何学Pythonr_id = ? OR id IN ( select post_id from reposts where user_id=? )", '1', '1'], :limit => 9)

It works fine, but:

I need to ORDER BY my @posts by a combine of two columns "created_at" (created_at of table POSTS and created_at of table REPOSTS)

Any help?


Try this:

class Post
  has_many :reposts
end


class Repost
  belongs_to :post
end    

Post.all(
  :include => :reposts, 
  :conditions => ["posts.user_id = ? OR reposts.user_id = ?", 1, 1],
  :order => "posts.created_at DESC, reposts.created_at DESC
)
0

精彩评论

暂无评论...
验证码 换一张
取 消