如何合并来自同一模型的两个查询的结果? [英] How do I combine results from two queries on the same model?

查看:52
本文介绍了如何合并来自同一模型的两个查询的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在视图中准确返回十条记录.我想使用一个限制性很强的查询,但我想要一个限制性较低的查询来填充结果,以防第一个查询没有产生 10 个结果.

I need to return exactly ten records for use in a view. I have a highly restrictive query I'd like to use, but I want a less restrictive query in place to fill in the results in case the first query doesn't yield ten results.

只是玩了几分钟,这就是我想出来的,但它不起作用.我认为它不起作用,因为合并是为了在不同模型上组合查询,但我可能是错的.

Just playing around for a few minutes, and this is what I came up with, but it doesn't work. I think it doesn't work because merge is meant for combining queries on different models, but I could be wrong.

class Article < ActiveRecord::Base
...
  def self.listed_articles
    Article.published.order('created_at DESC').limit(25).where('listed = ?', true)
  end

  def self.rescue_articles
    Article.published.order('created_at DESC').where('listed != ?', true).limit(10)
  end

  def self.current
    Article.rescue_articles.merge(Article.listed_articles).limit(10)
  end
...
end

在控制台中查看,这会强制对rescue_articles中的查询施加listed_articles中的限制,显示如下:

Looking in console, this forces the restrictions in listed_articles on the query in rescue_articles, showing something like:

Article Load (0.2ms)  SELECT `articles`.* FROM `articles` WHERE (published = 1) AND (listed = 1) AND (listed != 1) ORDER BY created_at DESC LIMIT 4
Article Load (0.2ms)  SELECT `articles`.* FROM `articles` WHERE (published = 1) AND (listed = 1) AND (listed != 1) ORDER BY created_at DESC LIMIT 6 OFFSET 4

我确定文档中缺少一些非常简单的方法,但我还没有找到.

I'm sure there's some ridiculously easy method I'm missing in the documentation, but I haven't found it yet.

我想要做的是返回最近 25 篇文章中列出的所有文章.如果这不能让我获得十篇文章,我想从最近列出的文章中添加足够多的文章,其中列出的文章不真实,以获得我的完整十篇文章.

What I want to do is return all the articles where listed is true out of the twenty-five most recent articles. If that doesn't get me ten articles, I'd like to add enough articles from the most recent articles where listed is not true to get my full ten articles.

编辑#2:换句话说,merge 方法似乎将查询串在一起以形成一个长查询,而不是合并结果.我需要两个查询的前十个结果(优先列出文章),而不是一个长查询.

EDIT #2: In other words, the merge method seems to string the queries together to make one long query instead of merging the results. I need the top ten results of the two queries (prioritizing listed articles), not one long query.

推荐答案

使用您的初始代码:

您可以使用 + 连接两个数组,然后获得前 10 个结果:

You can join two arrays using + then get first 10 results:

  def self.current
    (Article.listed_articles  +  Article.rescue_articles)[0..9]
  end

我想一种非常肮脏的做法是:

I suppose a really dirty way of doing it would be:

  def self.current
      oldest_accepted = Article.published.order('created_at DESC').limit(25).last
      Artcile.published.where(['created_at > ?', oldest_accepted.created_at]).order('listed DESC').limit(10)
  end

这篇关于如何合并来自同一模型的两个查询的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆