mysql - rails : order query by has and belongs to many presence

标签 mysql ruby-on-rails sql-order-by

我有以下事件记录模型:

class Catalog < ActiveRecord::Base
   has_and_belongs_to_many :customers
end

class Customer < ActiveRecord::Base
   has_and_belongs_to_many :catalogs
end

现在在我的索引中,我想列出所有按如下方式排序的客户: 首先是已经是目录成员的成员,然后是所有其他成员。

我尝试过这样的事情:

@customers = Customer.all.joins('LEFT JOIN catalogs_customers ON catalogs_customers.customer_id = customers.id').order('catalogs_customers.catalog_id DESC, customers.company_name ASC')

这接近我的目标,但我得到了目录成员的所有客户(无论是什么),然后是所有其他客户。

最佳答案

你的问题有点不清楚,但我无法发表评论来询问更多,所以无论如何我都会尽力而为。 听起来您想要列出所有客户,并优先考虑与一个特定目录相关的客户,但您的代码示例并没有告诉我们您计划如何设置。我假设您有一个实例变量@catalog_id。然后,您需要在加入时提供一个条件,仅选择具有该 catalog_idcatalogs_customers。所以尝试这样的事情:

@customers = Customer.all.joins('LEFT JOIN catalogs_customers ON catalogs_customers.customer_id = customers.id').
.where(catalogs_customers: { catalog_id: @catalog_id }).
order('catalogs_customers.catalog_id DESC, customers.company_name ASC')

希望有帮助。

关于mysql - rails : order query by has and belongs to many presence,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48749368/

相关文章:

ruby-on-rails - 简单形式未定义方法路径

mysql - 订购 UNION MySQL 查询时出错

mysql - 我无法在docker compose中进行mysql php artisan迁移。错误SQLSTATE [HY000] [2002]

ruby-on-rails - 提交者在 Ruby 社区中使用什么测试环境设置?

sql - 在 SQL 查询的 WHERE 子句中使用自定义字段

sql - ActiveRecord 查询返回对象两次(同一对象的 2 个实例)

mysql - 分页sql查询语法

mysql - 即使我只选择主键,带有“order by”的派生表也会使用临时表和文件排序

mysql - 如何使用 spring.jpa.hibernate.ddl-auto

mysql - Following 和 Followers Systems 的逻辑是什么?