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?

    打赏 评论

相关推荐 更多相似问题