2017-08-06 77 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(); 
}