Laravel获取每个用户的最新答案,其中Preferred = True

时间:2015-06-22 16:18:00

标签: mysql laravel count eloquent

我需要获取每个USER最近的ANSWER的COUNT,其中PREFERRED = TRUE。我有下面的查询,唯一的问题是我不知道如何只通过用户的最新答案进行过滤。

// Functions
function calc(){
    // Get Years
   var years = (document.getElementById('years').value);
   // Variables
   var years;
   var gallons = 1100 * 365;
   var grain = 45 * 365;
   var forest = 30 * 365;
   var co2 = 20 * 365;
   var animal = 1 * 365;
   // Calculations
   var gallonsTotal =  years * gallons;
   var grainTotal =  years * grain;
   var forestTotal =  years * forest;
   var co2Total =  years * co2;
   var animalTotal =  years * animal;
   //Prints
   document.querySelector('.gallons').innerHTML = "Gallons " + gallonsTotal;
   document.querySelector('.grain').innerHTML = "Gains " + grainTotal;
   document.querySelector('.forest').innerHTML = "Forest " + forestTotal;
   document.querySelector('.co2').innerHTML = "Co2 " + co2Total;
   document.querySelector('.animals').innerHTML = "Animals " + animalTotal;
};

如何过滤此选项以仅计算每个用户最近的答案,其中preferred = true?

1 个答案:

答案 0 :(得分:0)

根据您的上一条评论,我能够构建以下数据:

Data

然后,您只需执行以下查询:

SELECT SUM(t1.pref)
FROM answers AS t1
LEFT OUTER JOIN answers AS t2 ON t1.user_id = t2.user_id
    AND t1.created_at < t2.created_at
WHERE t2.user_id IS NULL

您可以将此查询作为raw expression运行,也可以对其进行Laravelize ...您的选择。但那是你想要的查询。

如果您想对每位用户选择的答案进行审核,您可以执行以下操作:

SELECT t1.*
FROM answers AS t1
LEFT OUTER JOIN answers AS t2 ON t1.user_id = t2.user_id
    AND t1.created_at < t2.created_at
WHERE t2.user_id IS NULL