postgresql Rails 连接查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13277938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 00:32:07  来源:igfitidea点击:

Rails joins query

ruby-on-railsruby-on-rails-3postgresqlactiverecord

提问by 1dolinski

I have three models

我有三个模型

  • Tag=> :id, :name
  • Tagging=> :id, :tag_id, :post_id
  • Post=> :id, :summary
  • Tag=> :id,:name
  • Tagging=> :id, :tag_id,:post_id
  • Post=> :id,:summary

I know the id of the tag. I would like to query for all of the posts that have a specific tag_id, through the Taggingsmodel.

我知道标签的 ID。我想tag_id通过Taggings模型查询所有具有特定,的帖子。

Something like

就像是

@post = Post.joins(:taggings).where(:tag_id => 17)

but this doesn't work because it is looking for the tag_id in the Postmodel and not the Taggingmodel.

但这不起作用,因为它正在寻找Post模型中的 tag_id而不是Tagging模型。

I'm not sure how to do this.

我不知道该怎么做。

回答by Raphael Abreu

I don't like to use string in ActiveRecord queries, so, I prefer this sintax:

我不喜欢在 ActiveRecord 查询中使用字符串,所以,我更喜欢这个语法:

@post = Post.joins(:taggings).where(taggings: {tag_id: 17})

回答by Alexandru Emil Lupu

First of all :

首先 :

 class Post < ActiveRecord::Base

   has_many :taggings
   has_many :tags, :through => :taggings 
 end

 class Taggins < ActiveRecord::Base 
   belongs_to :post 
   belongs_to :tag
 end

 class Tag < ActiveRecord::Base 
   has_many :taggings 
   has_many :posts, :through => :taggings 
 end

If you have the tag object you can do

如果你有标签对象,你可以做

 @posts = @tag.posts 

or

或者

 class Post < .... 
   ....
   def self.find_by_tag_id(tag_id)
      Post.joins(:taggings).where('taggings.tag_id = ?', tag_id)
   end
 end

回答by Tom Harrison

Using the .where format you can pass a string like .where("taggings.tag_id = ?", 17) to qualify the joined taggings table.

使用 .where 格式,您可以传递像 .where("taggings.tag_id = ?", 17) 这样的字符串来限定连接的标记表。

回答by 1dolinski

As @tharrison mentioned. A solution is:

正如@tharrison 提到的。一个解决办法是:

@post = Post.joins(:taggings).where("taggings.tag_id = ?", 17)