2017-08-06 75 views
0

我有一个名为Conversation的偶尔型号。如何在laravel 5.3中添加一个hasMany关系?

在这个模型中,我定义上的雄辩模型CallParticipant一个hasMany关系,像这样:

public function participants(){ 
    return $this->hasMany('App\Models\Purecloud\Analytics\CallParticipant', 'conversationId', 'conversationId'); 
} 

现在,CallParticipants可以系统进程,客户或代理商。我需要的是被认为是“代理人”,所以我这样定义的另一个关系的所有CallParticipants列表:

public function agents(){ 
     return $this->hasMany('App\Models\Purecloud\Analytics\CallParticipant', 'conversationId', 'conversationId') 
      ->whereIn('partPurpose', ['agent','user']); 
} 

现在,“代理”可以是一个“参与者”多次在“对话”,也就是说有可能只是用不同的participantId同一个代理多个行,像这样:

+----------------+---------------+--------------+-------------+ 
| conversationId | participantId | partUserName | partPurpose | 
+----------------+---------------+--------------+-------------+ 
|    1 |   100 | Alex   | agent  | 
|    1 |   101 | Mary   | agent  | 
|    1 |   102 | Alex   | agent  | <-- I want to exlcude this 
+----------------+---------------+--------------+-------------+ 

,我需要这样的关系,只返回一个排的每个partUserName(一行删除这些sortof,重复玛丽和亚历克斯一排)。

我试图通过添加GROUPBY这样做:

public function agents(){ 
    return $this->hasMany('App\Models\Purecloud\Analytics\CallParticipant', 'conversationId', 'conversationId') 
     ->whereIn('partPurpose', ['agent','user']) 
     ->groupBy('partUserName'); 
} 

但是,这会产生错误:

SQLSTATE[42000]: Syntax error or access violation: 1055 'analytics.callParticipants.participantId' isn't in GROUP BY

我也试过在with语句像下面这样做,但我得到相同的错误:

$conversations = Conversation::with(
     [ 
      'agents' => function($query){ 
       $query->groupBy('partUserName'); 
      } 
     ]) 
     ->get(); 

有没有什么办法可以限制关系以唯一的行partUserName

回答

0

我认为唯一的方法就是通过“黑客”关系。您可以尝试:

public function agents(){ 
    return $this->hasOne('App\Models\Purecloud\Analytics\CallParticipant', 'conversationId', 'conversationId') 
    ->whereIn('partPurpose', ['agent','user']) 
    ->latest(); 
}