mysql - 通过关联查询 OR 条件

标签 mysql sql ruby-on-rails activerecord ruby-on-rails-3.2

我正在尝试通过用户名或电子邮件帮助查找用户记录。唯一的问题是用户名存储在关联的 UserDetail 模型中。

class User
  has_one :user_detail

  def self.find_by_username_or_email(value)

    # This is effectively pseudocode for the query I'd like to write.
    query = "lower(email) = :value OR user_detail.username = :value"
    where([query, { value: value }]).first
  end
end

如何编写与关联的 user_detail 记录中的电子邮件或用户名匹配的查询?

最佳答案

你快到了!

这应该适合你:

class User < ActiveRecord::Base
  has_one :user_detail

  def self.find_by_username_or_email(value)
    query = "lower(users.email) = :value OR user_details.username = :value"
    includes(:user_detail).where(query, value: value).first
  end
end

关于mysql - 通过关联查询 OR 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18770668/

相关文章:

c# - 将 SQL 存储过程和参数存储在数据库表中是否是一种不好的做法

ruby-on-rails - rake 数据库 :create ruby on rails

php - 从数据库中选择随机表

mysql - SQL ORDER BY 与 UNION

php - 连接到不允许远程连接的主机上的 mysql 数据库

php - 选择大括号内的特定 sql 数据

mysql - Rails 关联不起作用,user_id 未显示在控制台中

ruby-on-rails - Rails 4 - 使用omniauth-google-oauth2的Google一次性代码流,不断收到 "Invalid code"

mysql - SQL:按 Select with Join 的结果删除

php - 如果电子邮件存在返回错误,否则添加 php mysql