Laravel:如何获得所有关系NOT count的count()

时间:2015-07-20 20:38:22

标签: laravel laravel-4

我有一个像这样的访问者

  public function getRegisteredCountAttribute()
  {
    return $this->attendees->count();

  }

但是,我注意到这会在查询后计算我的收藏中的与会者。因此,如果我的查询删除了一些与会者,我就无法获得正确的计数。

这是我的查询

        $programs = ScheduledProgram::where('registration_start_date', '<=', $today)
                                    ->where('end_date',                '>=',  $today)
/*                ->with(['attendees'=>function($q) use ($user_id)
                                        {
                                        $q->where('user_id', $user_id);
                                        }])
                                    ->with(['scheduledProgramSegments.attendees'=>function($q) use ($user_id)
                                        {
                                        $q->where('user_id', $user_id);
                                        }])
*/
                                    ->get();

当我取消注释上面的查询部分中的评论时,我从访问者$program->registered_count获得了不同的号码。我想访问者正在从集合中给我计数,而不是做一个新的查询来获得我真正需要的计数。

如何获得该计划中注册与会者的人数?

我应该注意,模型attendeesprograms与数据透视表具有多对多(belongsToMany)关系,该数据透视表也包含registered, waitlisted字段。

我看到this article但我找不到next belongsToMany

模型

class ScheduledProgram extends Eloquent { 
 public function scheduledProgramSegments()
  {
    return $this->hasMany('ScheduledProgramSegment');
  }
  public function attendees()
  {
    return $this->belongsToMany('Attendee', 'prog_bookings')->withPivot('registered','paid','waitlisted');
  }
  public function getRegisteredCountAttribute()
  {
    return $this->attendees()->count();
  }
}

class ScheduledProgramSegments extends Eloquent {
  public function attendees()
  {
    return $this->belongsToMany('Attendee', 'bookings')->withPivot('paid');
  }
  public function scheduledProgram()
  {
    return $this->belongsTo('ScheduledProgram');
  }
}

class ProgBooking extends Eloquent {
 public function scheduled_program()
  {
    return $this->belongsTo('ScheduledProgram');
  }
  public function attendee()
  {
    return $this->belongsTo('Attendee');
  }
}

1 个答案:

答案 0 :(得分:0)

当您获取 $ programs 并急切地加载与会者并带有一些额外约束时,这些已提取的过滤参与者将保存在 $ program-&gt;与会者属性。当您在该集合上调用 count()时,您将在该过滤集合中获得许多与会者。

如果您需要计算给定计划中的所有与会者,您需要这样做:

public function getRegisteredCountAttribute()
{
  return $this->attendees()->count();
}

请注意额外的() - 因此,您应该在急切加载的与会者集合中调用 count()并应用其他约束 - 您&# 39; ll称之为关系本身。