doujimiao7480
2014-10-13 19:40
浏览 852
已采纳

循环遍历每个元素的数组和MySQL查询 - 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.

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();

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?

图片转代码服务由CSDN问答提供 功能建议

我有一个包含网站列表的表格。 我还有一张表格,其中包含有关访问和转化的信息。 在此表中,我每个网站每天有一行,列访问次数和转化次数。 所以我知道哪个网站每天都有多少次访问和转换。

现在,我想在表格中列出所有网站,其中包含过去30年来本网站上的访问次数和转化次数。 几天。

所以我所做的是将所有网站加载到一个数组中:

  $ websites = Website :: all()  ; 
   
 
 

然后我遍历此数组以获取其他数据:

$ complete_list = array();

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

转化同样的事情。

这有效,但似乎没有 最好的方法...

有没有人知道如何简化?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douchuang1861 2014-10-13 20:06
    已采纳

    Have you thought about using Eager Loading? http://laravel.com/docs/4.2/eloquent#eager-loading

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题