In my database, I create three tables which are user, user_group, user_group_info.
I want to do something like this query, but i have no idea how can i join the two tables.
SELECT * FROM user AS u
INNER JOIN user_group AS ug ON u.user_group_id=ug.user_group_id
INNER JOIN user_group_info AS ugi ON ug.user_group_id=ugi.user_group_id
WHERE ugi.language_id = 1
User Model
class User < ApplicationRecord
self.table_name = "user"
self.primary_key = "user_id"
belongs_to :user_group
end
class UserGroup < ApplicationRecord self.table_name = "user_group" self.primary_key = "user_group_id" has_many :user belongs_to :user_group_info end
class UserGroupInfo < ApplicationRecord self.table_name = "user_group_info" has_many :user_group end
You can use ActiveRecord to create your query rather than creating it by hand. Try this:
User.joins(user_group: :user_group_info).where(user_group_infos: { language_id: 1 })
This should translate into what you gave as an example query in your question.
You start with User
and you join with user_groups
. Through user_groups
, you join with user_group_infos
. Finally, you add a condition on the user_group_infos
. There are a couple ways to write that.
where("user_group_infos.language_id = ?", language_id)
# or
where(user_group_infos: { language_id: language_id })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.