mysql - 从二维数组中获取值

标签 mysql ruby-on-rails arrays ruby

我已使用此查询来检索某一特定用户批准休假的日期 -

LeaveRequest.where(user_id: 6).where(status: 1).pluck(:from_date, :to_date)

我得到了这个数组作为结果 -

[[Mon, 12 Sep 2016, Fri, 16 Sep 2016], [Tue, 06 Sep 2016, Tue, 06 Sep 2016], [Thu, 01 Sep 2016, Fri, 02 Sep 2016], [Tue, 30 Aug 2016, Wed, 31 Aug 2016]] 

我想要的是获取所有日期以及2016年9月12日至2016年9月16日(13日、14日和15日)之间的日期。

最佳答案

我假设你的意思是这样的

require 'date'
#This is to simulate your current Array
current_array = 5.times.map {|n [Date.new(2016,n+1,1).<<(1),Date.new(2016,n+1,1)]}
#map the 2 dates to a Range
new_array = current_array.map{|start_date,end_date| (start_date..end_date)} 
new_array.first.class
#=> Range

在 Range 上调用 to_a 会将其扩展到 start_dateend_date 之间的所有日期

使用 Rails,你可以做类似的事情

class LeaveRequest
  def self.user_requested_ranges(user_id, status_id)
    scoped.
      where(user_id: user_id, status: status_id).
      pluck(:from_date, :to_date).
      map do |from_date, to_date|
        #optionally to output the full Array in each Range you could use 
        #(from_date..to_date).to_a  
        (from_date..to_date)
      end
  end
end

然后调用为

LeaveRequest.user_requested_ranges(6,1)

关于mysql - 从二维数组中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39229748/

相关文章:

mysql windows 远程访问

sql - 有效地找到 "record high"值

javascript - 更改两个数组总是同时更改另一个数组

具有模式修改语句 (DDL) 的 MySQL 事务?

mysql - 使用多表连接获取表行数

ruby-on-rails - capybara :查找(元素)使用选择器来定位复杂的属性名称

ruby-on-rails - 从 ActiveRecord 获取表名

java - 如何打印 List<Object[]> 值?

arrays - 如何编写 VBA 用户定义函数以使用 ctrl+shift+enter 从 IF 获取数组参数?

php - Laravel 数据库优化