Laravel统计相关数据

时间:2014-05-14 18:11:07

标签: php laravel eloquent

我在我的数据库中:

Campaigns
    hasMany Tasks
        hasMany Links
            hasMany LinkClicks

如果我查询

Campaign::find(1)->task->count();

它会返回与该广告系列相对应的正确任务数。 但是,我如何计算来自广告系列ID的链接点击次数?

广告系列模型:

public function task(){
    return $this->hasMany('Task','campaign_id');
}

任务模型:

public function campaign(){
    return $this->belongsTo('Campaign','campaign_id');
}
public function links(){
    return $this->hasMany('Link','task_id');
}

链接模型:

public function task(){
    return $this->belongsTo('Task','task_id');
}
    public function clicks(){
            return $this->hasMany('LinkClick', 'link_id');
    }
public function user(){
    return $this->belongsTo('User','user_id');
}

LinkClick模型:

public function link(){
    return $this->belongsTo('Link','link_id');
}

所以,我想只计算特定Campaign下的链接的链接点数,无论哪个任务或链接,当前任务和链接都需要在指定的Campaign下。

3 个答案:

答案 0 :(得分:4)

使用hasManyThrough作为链接:

// Campaign model
public function links()
{
   return $this->hasManyThrough('Link', 'Task');
}

// then you can fetch the count either querying db:
$campaign->links()->count(); // SELECT COUNT(*) ...
// returns STRING '25'

// or from the collection of already loaded relation:
$campaign->links->count(); // counts collection items
// returns INT 25

对于LinkClicks来说,这不会更进一步,但是你可以轻松实现这一目标:

// This is another way for the above:
$campaign = Campaign::with('tasks.links')->find($someId);
$campaign->tasks->fetch('links')->collapse()->count(); // INT 25

// and the LinkClicks:
$campaign = Campaign::with('links.clicks')->find($someId);
$campaign->links->fetch('clicks')->collapse()->count(); // INT 555

答案 1 :(得分:2)

由于它们都是“hasMany”关系,因此您需要迭代每个级别的所有子级以生成总和。这样的事情应该适合你:

$campaign = Campaign::find($campaignId);

$count = 0;
foreach($campaign->task as $task) {
    foreach($task->link as $link) {
        $count += $link->click->count();
    }
}

echo 'Clicks for campaign id ' . $campaignId . ': ' . $count . "\n";

或者,您可以跳过所有这些,只发出针对数据库的裸声明:

$results = DB::select(
    'SELECT \'a\' FROM campaign c
        INNER JOIN task t ON t.campaign_id = c.id
        INNER JOIN links l ON t.task_id = t.id
        INNER JOIN link_clicks lc ON lc.link_id = l.id'
);

然而,第一个想法可能是一个更好的主意。

答案 2 :(得分:0)

因为你正在使用关系;你可以这样做:

$count = 0;
$campaign_with_tasks = Campaign::with('tasks')->where('id','=',$campaign_id)->get();

foreach($campaign_with_tasks->tasks as $task){
$links =  Links::where('task_id','=',$task->id)->get();
foreach($links as $link){
$count += LinkClicks::where('link_id','=',$link->id)->count();
}
}