【发布时间】:2016-12-08 12:17:12
【问题描述】:
首先我为标题道歉,我找不到更好的东西。
在我的项目中,我有用户和组。用户可以加入群组并创建群组。关系定义如下。
用户模型
/** Get all the groups the user is administrator of
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function groupsAdmin()
{
return $this->hasMany('App\Group','group_admin_id','id');
}
组模型
/** Get the users in a group
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function users()
{
return $this->belongsToMany(\App\User::class,'groups_users', 'group_id','user_id');
}
我要做的是获取所有加入用户创建的组的用户。为此,我在我的用户模型中编写了一个方法:
/**
* Returns all the users who have attended groups created by this user
*/
public function getPastGroupAttendees()
{
// first verify if the user is admin of any group
if(!$this->groupsAdmin)
{
return false;
}
$attendees = array();
foreach($this->groupsAdmin as $group)
{
if(count($group->users) > 0) $attendees[] = $group->users;
}
return $attendees;
}
但是这种方法的问题是它的速度很慢,并且会随着新数据而变慢。而且由于用户可以加入多个组,我会从这种方法中获得重复的用户。 因此,如果有人可以向我展示一些优化和纠正此问题的方向,那将非常有帮助。
【问题讨论】: