简体   繁体   中英

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.

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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