【问题标题】:Sequel making the following one query running an exclude from a join table继续执行以下一个查询,从连接表中运行排除
【发布时间】:2015-04-29 00:40:06
【问题描述】:

我有一个users 表和一个blocked_users 表。 users 拥有我所有的身份验证数据、网站偏好等,blocked_users 拥有 source_idtarget_id

我想返回一个用户未屏蔽且当前用户未屏蔽的所有用户的集合。

现在我有以下代码,我通过调用@user.available_users 执行,但它执行三个查询。有什么方法可以让这个查询成为一个单一的查询吗?

class User < Sequel::Model

  one_to_many :blocked_users,     :key=>:source_id
  one_to_many :blocked_by_users,  :key=>:target_id, :class => BlockedUser

  def block_user(id)
    BlockedUser.create({source_id:self.id, target_id:id})
  end 

  def blocked_user_ids
    self.blocked_users.map{|bu| bu[:target_id]}
  end 

  def blocked_by_user_ids
    self.blocked_by_users.map{|bu| bu[:target_id]}
  end 

  def available_users
    User.exclude(:id=>self.blocked_users.map{|bu| bu[:target_id]}).exclude(:id=>self.blocked_by_users.map{|bu| bu[:target_id]})
  end 
end

我在我的 User 类中添加了以下方法:

  def test_avail
    User.exclude(:blocked_users=>self).exclude(:blocked_by_users=>self)
  end 

1.9.3p0 :001 > User.all.first.test_avail
   INFO - (0.000732s) SELECT * FROM `users`
Sequel::Error: invalid association class User for association :blocked_users used in dataset filter for model User, expected class BlockedUser

【问题讨论】:

    标签: ruby sequel


    【解决方案1】:

    通过关联支持使用过滤器可能是最简单的:

    def available_users
      User.exclude(:blocked_users=>self).exclude(:blocked_by_users=>self)
    end
    

    【讨论】:

    • 嘿,所以我在上述问题中添加了更改,但现在有了那个 sn-p,我得到 Sequel::Error: invalid association class User for association :blocked_users used in dataset filter for model User, expected class屏蔽用户
    • 我的错。如果blocked_users 和blocked_by_users 是自引用的many_to_many 关联,则该代码将起作用。相反,您使用的是单独的 BlockedUser 类和 one_to_many 关联。我不确定你为什么要这样设置。使用您当前的代码,您应该能够执行 User.exclude(:id=>self.blocked_users_dataset.select(:target_id))。
    猜你喜欢
    • 2021-10-02
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 2018-09-23
    相关资源
    最近更新 更多