2017-05-24 69 views
0

我在Laravel 5.4上遇到了一個問題,當我嘗試只使用一個連接時,它工作正常並返回正確的數據,但是他們添加了另一個連接,無法正常工作。Laravel加入多張表格無法正常工作

$data = Player::select(DB::raw('CONCAT(familyName,", ",firstName) AS fullName')) 
    ->where('firstname', 'like', '%'.$search.'%') 
    ->orWhere('familyName', 'like', '%'.$search.'%') 
    ->orderBy('familyName', 'asc') 
    ->join('teams', 'players.primaryClubId', '=', 'teams.clubId') 
    ->join('person_competition_statistics', 'players.personId', '=', 'person_competition_statistics.personId') 
    ->addSelect(['players.*', 'teams.teamName', 'teams.teamNickname', 'teams.teamCode']) 
    ->get() 
    ->unique() //remove duplicates 
    ->groupBy(function($item, $key) { //group familyName that starts in same letter 
     return substr($item['familyName'], 0, 1); 
    }) 
    ->map(function ($subCollection) { 
     return $subCollection->chunk(4); // put your group size 
    }); 

return $data; 

返回錯誤:

QueryException in Connection.php line 647: 
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'familyName' in field list is ambiguous (SQL: select CONCAT(familyName,", ",firstName) AS fullName, `players`.*, `teams`.`teamName`, `teams`.`teamNickname`, `teams`.`teamCode` from `players` inner join `teams` on `players`.`primaryClubId` = `teams`.`clubId` inner join `person_competition_statistics` on `players`.`personId` = `person_competition_statistics`.`personId` where `firstname` like %% or `familyName` like %% order by `familyName` asc) 
+0

您是否在所有加入的3個表中的多個表中都有「familyName」列?如果是這樣,你需要在查詢中使用表名的前綴。像'DB :: raw('CONCAT(players.familyName,「,」,firstName)AS fullName')' – ayip

+0

感謝您的幫助@ayip,它現在正在工作 – PenAndPapers

+0

@PenAndPapers如果你加入表,那麼你應該給表別名。像球隊一樣t,球員作爲p,然後列名像p.playername –

回答

1

如果要加入表,那麼你應該給表的別名。像t一樣的球員,球員作爲p,然後列名像p.playername

+0

謝謝@NikhilRadadiya – PenAndPapers