我有3个表用户(id,name等),trip(id,user_id,from,to,destionation),vactions(id,user_id,from,to,destionation)。 我使用mysqli,我无法弄清楚如何做到这一点 我需要像这样获取这个表
Array ( [0] => Array ( [id] => 1 [current_status] => 0 [username] => user1 [fullname] => Eric Norman [trips] = > Array ( [0] => Array ( [date_from] = 02/06/14 [date_to] = 05/06/14 [destination] = "Grece" ) [vacations] = > ) [1] => Array ( [id] => 2 [current_status] => 0 [username] => user2 [fullname] => Joe Grey [trips] = > Array ( [0] => Array ( [date_from] = 02/06/14 [date_to] = 05/06/14 [destination] = "Grece" ) [vacations] = > ) )
我尝试使用左连接,但我没有工作,我的代码现在只适用于用户:
conn = new mysqli($host,$user,$password,$db); $result = mysqli_query($conn, "SELECT id, current_status, username, CONCAT(first_name,' ',last_name) as fullname FROM user"); while ($row = $result->fetch_assoc()) { $users[] = $row; }
答案 0 :(得分:2)
我认为最好的办法是吸引所有用户,然后使用foreach来获取所有旅行和休假。 因为我不确定你是否可以使用简单的SQL查询获得这种数组结果,我认为你需要一个ORM。
$users = getAllUsers();
foreach($users as $user){
$user['trips'] = getTripsByUserId($user['id']);
$user['vacations'] = getVacationsByUserId($user['id']);
}
当然你需要编写3个方法“getAllUsers”; “getTripsByUserId”和“getVacationsByUserId”只是对带有where子句的数据库的简单SELECT查询。