简体   繁体   English

遍历数组和每个元素的MySQL查询-Laravel

[英]Loop through array and MySQL query for each element - Laravel

I have a table with a list of websites. 我有一张带有网站列表的表格。 Also I have a table with information about visits and conversions. 另外,我还有一张表格,其中包含有关访问和转化的信息。 In this table I have one row per website per day with columns visits and conversions. 在此表中,每个网站每天都有一行,其中包含访问次数和转化次数。 So I know which website had how many visits and conversions every day. 因此,我知道哪个网站每天有多少访问和转化。

Now, I want to list all websites in a table with the sum of visits and conversions on this website over the last 30 days. 现在,我想在表格中列出所有网站,以及过去30天内该网站的访问次数和转化次数之和。

So what I do is I load all websites into an array with: 所以我要做的是将所有网站加载到一个数组中:

$websites = Website::all();

And then I loop through this array to get the additional data: 然后循环遍历此数组以获取其他数据:

$complete_list = array(); $ complete_list = array();

foreach ($websites as $website) {

    $clicks = Stats::where(DATE INSIDE DATE RANGE)->where('website_id', '=', $website->id)->sum('visits');
    $complete_list[] = array(
       'website' => $website->id,
       'click'=> $clicks
    }; 
}

Same thing for conversions. 转换也一样。

This works but does not seem the best way to do this... 这可行,但似乎不是做到这一点的最佳方法...

Does anyone have an idea on how to simplify? 有没有人有关于如何简化的想法?

Have you thought about using Eager Loading? 您是否考虑过使用“急切加载”? http://laravel.com/docs/4.2/eloquent#eager-loading http://laravel.com/docs/4.2/eloquent#eager-loading

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM